Android Studio Firebase Instagram Clone

Uygulamalarımız için kullanabileceğimiz bir veritabanı olarak karşımıza çıkan Firebase bir çok özelliği sayesinde bizlere oldukça kolaylık sağlıyor. Firebase kütüphanesi Database(Veri Tabanı), Storage(Media Depolama) ve Authentication(Kimlik Doğrulama) özelliklerini bizlere sunmaktadır. Bizde bu makalede her bir özelliği kullanarak basit bir uygulama yapmaya çalışacağız.
Uygulamamızı genel olarak anlatırsak ilk olarak kullanıcı telefonunda bulunan bir resimi seçerek resim ile ilgili bir yorum ekleyecek daha sonra bu resim ve yorumu veritabanına kayıt edeceğiz. Seçilen resim ve yorumu bir sayfada instagrama benzer bir şekide göstereceğiz. Kullanıcılar resimin üstüne basılı tuttuğu zaman da resim beğenilmiş olacak kısaca instagramın ilkel bir hali şeklinde karşımıza çıkacak.
Bir resim post ettiğimiz zaman veya bir resimi beğendiğimiz zaman diğer kullanıcının aynı anda değişikliği algılamasını Firebase kütüphanesinin Real Time özelliği sağlamaktadır böylelikle sadece Instagram değil Whatsapp gibi uygulamalarında yapılabilmesi için oldukça kullanışlı bir veritabanıdır.
GEREKLİ AYARLARIN YAPILMASI
1 – Android Studio >> Start a new Android Studio project diyerek yeni bir proje oluşturuyoruz.
2 – Üst pencereden Firebase>>Tools sekmesini açıyoruz ve aşağıdaki resimlerde numaralı yerleri aktif hale getiriyoruz.
En son hali aşağıdaki resim gibi olması gerekiyor.
Resimdeki adımları uyguladığımız zaman Firebase kütüphanesinin Authentication özelliğini aktif hale getirip uygulamamıza dahil etmiş olduk. Database ve Storage özelliklerini kullanabilmek için aynı adımları bu özellikler için de uyguluyoruz.
3 – AndroidManifest.xml dosyamızı açıp aşağıdaki izinleri alıyoruz.
1 2 3 |
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/> |
4 – Uygulamamızda kullanacağım resimleri buraya tıklayarak indirelim ve klasördeki üç resimi drawable klasörünün altına atalım.
5 – Uygulamanın yukardaki çalışan gifine dikkat ederseniz post işlemini yapmak için sağ üstte bulunan üç noktaya tıklayarak bir menü açıyoruz. Bu şekilde bir menü oluşturabilmek için bu adımı uyguluyoruz.
res klasörünün üstüne sağ tıklayarak new >> Directory diyerek menu adında bir klasör oluşturuyoruz. Daha sonra oluşturduğumuz menu klasörünün üstüne sağ tıklayarak new >> Menu resource file diyoruz File name kısmına add_post diyerek yeni xml dosyası oluşturuyoruz. Oluşturduğumuz xml dosyasını aşağıdaki gibi düzenliyoruz.
add_post.xml
1 2 3 4 5 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/add_post" android:title="Add Post"></item> </menu> |
6 – Resimleri veritabanına kayıt ederken url şeklinde kayıt edeceğiz. Uygulamamızda bu resimleri gösterebilmek için oldukça karışık işlemler yapmak yerine Picasso Freamwork’ü kullanacağız. Buraya tıklayarak websitesini ziyaret edebilirsiniz.
Kullanımı kolay olduğu gibi kurulumuda oldukça kolay aşağıdaki kod satırını build.gradle dosyamıza ekliyoruz.
1 |
compile 'com.squareup.picasso:picasso:2.5.2' |
Gerekli ayarları 6 adımda yaptıktan sonra projemiz anlatıma geçmek için hazır hale geldi artık anlatıma geçelim.
activity_main.xml dosyamızı email ve şifre girilebilecek şekilde bir login sayfası oluşturuyoruz.
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.esatgozcu.firebaseinstagramclone.MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="250dp" android:layout_height="125dp" android:layout_marginTop="32dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/logo" /> <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sign up to see photos and " android:textStyle="bold" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="videos from your friends." android:textStyle="bold" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/text1" /> <EditText android:id="@+id/emailText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:ems="10" android:hint="Kullanıcı Adınızı Giriniz" android:inputType="textPersonName" android:text="" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/text2" /> <EditText android:id="@+id/passwordText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:ems="10" android:hint="Şifrenizi Giriniz" android:inputType="textPassword" android:text="" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/emailText" /> <Button android:id="@+id/signIn" android:layout_width="80dp" android:layout_height="35dp" android:layout_marginTop="32dp" android:background="#3897f0" android:onClick="signIn" android:text="Sign In" android:textAllCaps="false" android:textColor="@android:color/white" android:textSize="18sp" app:layout_constraintStart_toStartOf="@+id/passwordText" app:layout_constraintTop_toBottomOf="@+id/passwordText" /> <Button android:id="@+id/signUp" android:layout_width="80dp" android:layout_height="35dp" android:layout_marginTop="32dp" android:background="#3897f0" android:onClick="signUp" android:text="Sign Up" android:textAllCaps="false" android:textColor="@android:color/white" android:textSize="18sp" app:layout_constraintEnd_toEndOf="@+id/passwordText" app:layout_constraintTop_toBottomOf="@+id/passwordText" /> <TextView android:id="@+id/text3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="By signing up, you agree to our " android:textSize="16sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/signIn" /> <TextView android:id="@+id/text4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Terms Privacy Policy." android:textAlignment="center" android:textSize="16sp" android:textStyle="bold" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/text3" /> </android.support.constraint.ConstraintLayout> |
MainActivity.java sınıfımızda kullanıcının sisteme kayıt olmasını ve kayıt olduktan sonra giriş yapması için gerekli ayarları yapıyoruz.
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
package com.example.esatgozcu.firebaseinstagramclone; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { EditText emailText; EditText passwordText; Button signIn; Button signUp; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); emailText =(EditText)findViewById(R.id.emailText); passwordText = (EditText)findViewById(R.id.passwordText); signIn = (Button)findViewById(R.id.signIn); signUp = (Button)findViewById(R.id.signUp); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { // Mevcut kullanıcıda bir değişiklik olduğunda buradan kontrol edebiliriz. } }; } // signIn butonuna basıldığında.. public void signIn (View view) { mAuth.signInWithEmailAndPassword(emailText.getText().toString(),passwordText.getText().toString()) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Giriş başarılı olursa.. Intent intent = new Intent(getApplicationContext(),FeedActivity.class); startActivity(intent); Toast.makeText(getApplicationContext(),"Giriş Başarılı",Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Eğer bir hata ile karşılaşılırsa hatayı gösteriyoruz. Toast.makeText(getApplicationContext(),e.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show(); } }); } // signUp butonuna basıldığında.. public void signUp (View view) { mAuth.createUserWithEmailAndPassword(emailText.getText().toString(),passwordText.getText().toString()) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // İşlem başarılı olursa.. Toast.makeText(getApplicationContext(), "Kullanıcı Oluşturuldu",Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e != null) { // Eğer bir hata ile karşılaşılırsa hatayı gösteriyoruz. Toast.makeText(getApplicationContext(), e.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show(); } } }); } @Override protected void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override protected void onStop() { super.onStop(); if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } } } |
Kullanıcı kayıt olduktan sonra sisteme girdiğinde FeedActivity.java sınıfına geçiş yapacak ve bu sayfada adapter oluşturup listView içine aktararak resimleri göstereceğiz.
java klasörünün üstünde sağ tıklayarak new >> activity >> Empty Activity
Activity Name : FeedActivity
Layout Name : activity_feed
Finish diyerek dosyalarımızı oluşturuyoruz.
Oluşturduğumuz dosyaları aşağıdaki gibi düzenliyoruz.
FeedActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
package com.example.esatgozcu.firebaseinstagramclone; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class FeedActivity extends AppCompatActivity { ArrayList<String> useremailsFromFB; ArrayList<String> userimageFromFB; ArrayList<String> usercommentFromFB; ArrayList<String> userlikeFromFB; ArrayList<String> userIdFromFB; FirebaseDatabase firebaseDatabase; DatabaseReference myRef; PostClass adapter; ListView listView; // Menü kullanmak için gerekli methodu ovveride ediyoruz @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.add_post,menu); return super.onCreateOptionsMenu(menu); } // Menüde item seçtiğimiz zaman ne olacağını yönetiyoruz. @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.add_post) { // UploadActivity sınıfına geçiş yapıyoruz. Intent intent = new Intent(getApplicationContext(),UploadActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feed); useremailsFromFB = new ArrayList<String>(); usercommentFromFB = new ArrayList<String>(); userimageFromFB = new ArrayList<String>(); userlikeFromFB = new ArrayList<String>(); userIdFromFB = new ArrayList<String>(); firebaseDatabase = FirebaseDatabase.getInstance(); myRef = firebaseDatabase.getReference(); adapter = new PostClass(useremailsFromFB,userimageFromFB,usercommentFromFB,userlikeFromFB,userIdFromFB,this); listView = (ListView) findViewById(R.id.listView); listView.setAdapter(adapter); getData(); // Listede bulunan itemlere uzun basılı tutulduğu zaman ne olacağını yönetiyoruz. listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // Uzun basıldığı zaman beğeni sayısını artırıyoruz. // Beğeni sayısını ArrayList içinden çekiyoruz. int like = Integer.parseInt(userlikeFromFB.get(position)); like++; String stringLike = String.valueOf(like); String saveId =userIdFromFB.get(position); // Beğeni sayısını artırdıktan sonra veritabanında güncelliyoruz. myRef.child("Posts").child(saveId).child("like").setValue(stringLike); return false; } }); } private void getData() { DatabaseReference newReference = firebaseDatabase.getReference("Posts"); newReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // ArrayListleri temizliyoruz.. useremailsFromFB.clear(); userimageFromFB.clear(); usercommentFromFB.clear(); userlikeFromFB.clear(); userIdFromFB.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { // Veritabanından çektiğimiz verileri ArrayListlere aktarıyoruz. HashMap<String, String> hashMap = (HashMap<String, String>) ds.getValue(); useremailsFromFB.add(hashMap.get("useremail")); userimageFromFB.add(hashMap.get("downloadurl")); usercommentFromFB.add(hashMap.get("comment")); userlikeFromFB.add(hashMap.get("like")); userIdFromFB.add(hashMap.get("id")); // adapter'e değişiklik olduğunu bildiriyoruz. adapter.notifyDataSetChanged(); } // Son eklenen verileri en üstte gözükmesi için dizileri ters çeviriyoruz. Collections.reverse(useremailsFromFB); Collections.reverse(userimageFromFB); Collections.reverse(usercommentFromFB); Collections.reverse(userlikeFromFB); Collections.reverse(userIdFromFB); } @Override public void onCancelled(DatabaseError databaseError) { } }); } } |
activity_feed.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.esatgozcu.firebaseinstagramclone.FeedActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.constraint.ConstraintLayout> |
FeedActivity sınıfımızda adapter modeli için;
java klasörünün üstünde sağ tıklayarak new >> Java Class
Activity Name : PostClass
Ok diyerek dosyamızı oluşturuyoruz.
Oluşturduğumuz dosyayı aşağıdaki gibi düzenliyoruz.
PostClass.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.example.esatgozcu.firebaseinstagramclone; import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class PostClass extends ArrayAdapter<String> { private final ArrayList<String> useremail; private final ArrayList<String> userImage; private final ArrayList<String> userComment; private final ArrayList<String> userLike; private final ArrayList<String> userId; private final Activity context; public PostClass(ArrayList<String> useremail, ArrayList<String> userImage, ArrayList<String> userComment, ArrayList<String> userLike ,ArrayList<String> userId,Activity context) { super(context, R.layout.custom_view,useremail); this.useremail = useremail; this.userImage = userImage; this.userLike = userLike; this.userComment = userComment; this.userId = userId; this.context = context; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater layoutInflater = context.getLayoutInflater(); View customView = layoutInflater.inflate(R.layout.custom_view,null,true); TextView useremailText = (TextView) customView.findViewById(R.id.username); TextView commentText = (TextView) customView.findViewById(R.id.commentText); ImageView imageView = (ImageView) customView.findViewById(R.id.imageView2); TextView like = (TextView) customView.findViewById(R.id.like); useremailText.setText(useremail.get(position)); commentText.setText(userComment.get(position)); like.setText(userLike.get(position)); Picasso.with(context).load(userImage.get(position)).into(imageView); return customView; } } |
FeedActivity sınıfımızda listView içinde resimlerimiz daha derli toplu gösterebilmek için custom_view oluşturuyoruz zaten PostClass sınıfında bu xml dosyasını bağlamıştık.
layout klasörünün üstünde sağ tıklayarak New >> Layout resource file
File name : custom_view
Ok diyerek dosyamızı oluşturuyoruz.
Oluşturduğumuz dosyayı aşağıdaki gibi düzenliyoruz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:weightSum="1"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:id="@+id/imageView3" android:layout_width="50dp" android:layout_height="30dp" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:layout_weight="1" app:srcCompat="@drawable/avatar" /> <TextView android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="2dp" android:layout_marginTop="5dp" android:layout_weight="1" android:paddingBottom="10dp" android:paddingLeft="9dp" android:paddingTop="7dp" android:text="Mail alanı" android:textAlignment="textStart" android:textColor="@android:color/black" android:textSize="10sp" /> </LinearLayout> <TextView android:id="@+id/commentText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:paddingBottom="10dp" android:paddingLeft="10dp" android:paddingTop="10dp" android:text="Yorum alanı" android:textColor="@android:color/black" android:textSize="14sp" /> <ImageView android:id="@+id/imageView2" android:layout_width="match_parent" android:layout_height="300dp" android:padding="5dp" android:scaleType="fitXY" app:srcCompat="@mipmap/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="35dp" android:orientation="horizontal" android:padding="5dp"> <ImageView android:id="@+id/imageView4" android:layout_width="5dp" android:layout_height="20dp" android:layout_weight="1" android:scaleType="fitCenter" app:srcCompat="@drawable/heart" /> <TextView android:id="@+id/like" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="300dp" android:layout_weight="1" android:text="0" android:textAlignment="textStart" android:textColor="@android:color/black" /> </LinearLayout> </LinearLayout> |
Uygulamanın sağ üstünden menü >> add post dediğimiz zaman resimleri yükleyeceğimiz sayfayı nasıl düzenleyeceğimize bakalım.
java klasörünün üstünde sağ tıklayarak new >> activity >> Empty Activity
Activity Name : UploadActivity
Layout Name : upload_activity
Finish diyerek dosyalarımızı oluşturuyoruz.
Oluşturduğumuz dosyaları aşağıdaki gibi düzenliyoruz.
UploadActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
package com.example.esatgozcu.firebaseinstagramclone; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.IOException; import java.util.UUID; public class UploadActivity extends AppCompatActivity { Button commentButton; EditText commentText; ImageView imageView; Uri selected; FirebaseDatabase firebaseDatabase; DatabaseReference myRef; private FirebaseAuth mAuth; private StorageReference mStorageRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.upload_activity); commentButton =(Button)findViewById(R.id.postButton); commentText = (EditText)findViewById(R.id.commentText); imageView = (ImageView) findViewById(R.id.imageView); firebaseDatabase = FirebaseDatabase.getInstance(); myRef = firebaseDatabase.getReference(); mAuth = FirebaseAuth.getInstance(); mStorageRef = FirebaseStorage.getInstance().getReference(); } // Post butonuna tıklanırsa.. public void post (View view) { // Resimleri her seferinde eşsiz isimlerle kayıt etmek için UUID nesnesi türetiyoruz UUID uuidImage = UUID.randomUUID(); String imageName = uuidImage+".jpg"; StorageReference storageReference = mStorageRef.child("media").child(imageName); storageReference.putFile(selected).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // Yüklediğimiz resimin url'sini alıyoruz daha sonra bu url üzerinde resimi göstereceğiz. String downloadURL = taskSnapshot.getDownloadUrl().toString(); // Mevcut kullanıcıyı userEmail değişkenine aktarıyoruz daha sonra göstereceğiz. FirebaseUser user = mAuth.getCurrentUser(); String userEmail = user.getEmail().toString(); String userComment = commentText.getText().toString(); // Postları her seferinde benzersiz sayılarla kayıt etmek için key üretiyoruz. String id = myRef.push().getKey(); // Veri tabanına kayıt işlemini gerçekleştiriyoruz. myRef.child("Posts").child(id).child("useremail").setValue(userEmail); myRef.child("Posts").child(id).child("comment").setValue(userComment); myRef.child("Posts").child(id).child("downloadurl").setValue(downloadURL); myRef.child("Posts").child(id).child("id").setValue(id); // Beğenileri göstermek için like child oluşturuyoruz. myRef.child("Posts").child(id).child("like").setValue("0"); Toast.makeText(getApplicationContext(),"Post Başarılı",Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(),FeedActivity.class); startActivity(intent); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Hata ile karşılaşılırsa hatayı gösteriyoruz. Toast.makeText(getApplicationContext(),e.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show(); } }); } // Resim seçmek için üstene tıklanırsa basılırsa.. public void choose (View view) { // İzin verilip verilmediğini kontrol ediyoruz if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ // İzin verimemiş ise izin istiyoruz requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},1); } else { // İzin verilmiş ise galerisine gidiyoruz. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent,2); } } // Sorulan izinin sonucunu değerlendiriyoruz @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 1) { if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Eğer sorulan izine olumlu yanıt verirse galerisine gidiyoruz. Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent,2); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } // Galerisine gittikten sonra yapmış olduğu seçimi değerlendiriyoruz. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 2 && resultCode == RESULT_OK && data != null) { // Eğer bir resim seçildiyse ve boş değilse.. selected = data.getData(); try { // imageView' seçtiğimiz resimi gösteriyoruz. Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selected); imageView.setImageBitmap(bitmap); } catch (IOException e) { // Bir hata ile karşılaşılırsa.. e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } } |
upload_activity.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.esatgozcu.firebaseinstagramclone.UploadActivity"> <ImageView android:id="@+id/imageView" android:layout_width="368dp" android:layout_height="237dp" android:layout_marginEnd="5dp" android:layout_marginStart="5dp" android:layout_marginTop="32dp" android:onClick="choose" android:src="@drawable/logo" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/commentText" android:layout_width="324dp" android:layout_height="53dp" android:layout_marginTop="70dp" android:ems="10" android:hint="Yorumunuzu Giriniz.." app:layout_constraintEnd_toEndOf="@+id/imageView" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintStart_toStartOf="@+id/imageView" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <Button android:id="@+id/postButton" android:layout_width="188dp" android:layout_height="45dp" android:layout_marginTop="32dp" android:background="#3897f0" android:onClick="post" android:text="Post" android:textColor="@android:color/white" android:textSize="22sp" android:textStyle="bold" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/commentText" /> </android.support.constraint.ConstraintLayout> |
Böylelikle uzun bir anlatımdan sonra basit bir şekilde instagram mantığı ile çalışan bir uygulamayı nasıl yapabileceğimizi ve Firebase kütüphanesinin bize sağlamış olduğu Authentication – Database – Storage özelliklerini nasıl kullanabileceğimiz görmüş olduk.
Projenin kaynak kodlarını buraya tıklayarak indirebilirsiniz.