We had known the way to upload/download data. In this tutorial, we’re gonna look at way to get list of files example – display list of Images with Firebase UI Database FirebaseRecyclerAdapter
.
Related Posts:
– Firebase Storage β Upload Data from Memory, Local File, Stream | Android
– Firebase Storage β Download Files to Memory, Local File | Android
I. How to do
To display list of Images, we need to:
– add Firebase to Android App & enable Firebase Auth
– use Firebase Cloud Storage to upload and store images
– use Firebase Realtime Database to store images’ information (name + url)
– use FirebaseRecyclerAdapter
to display images in RecyclerView
with the help of Picasso lib.
To know way to add Firebase to Android App & enable Firebase Auth, please visit previous post:
Firebase Storage β Upload Data from Memory, Local File, Stream | Android
1. Upload and store images
Use Firebase Cloud Storage:
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 |
// store image at "images/filename.extension" on Firebase Cloud Storage imageReference = FirebaseStorage.getInstance().getReference().child("images"); fileRef = imageReference.child(fileName + "." + getFileExtension(fileUri)); fileRef.putFile(fileUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { String name = taskSnapshot.getMetadata().getName(); String url = taskSnapshot.getDownloadUrl().toString(); // use Firebase Realtime Database to store [name + url] writeNewImageInfoToDB(name, url); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // ... } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { // progress percentage double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount(); // percentage in progress dialog progressDialog.setMessage("Uploaded " + ((int) progress) + "%..."); } }) .addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() { @Override public void onPaused(UploadTask.TaskSnapshot taskSnapshot) { // ... } }); |
2. Store images’ information
Use Firebase Realtime Database:
1 2 3 4 5 6 7 8 |
mDataReference = FirebaseDatabase.getInstance().getReference("images"); private void writeNewImageInfoToDB(String name, String url) { UploadInfo info = new UploadInfo(name, url); String key = mDataReference.push().getKey(); mDataReference.child(key).setValue(info); } |
3. Display list of Images
3.1 Model and ViewHolder
– Model
class is a class that represents the data from Firebase:
1 2 3 4 5 6 7 |
public class UploadInfo { public String name; public String url; // ... } |
– ViewHolder
layout (R.layout.item_image) with UI items that correspond to Model
fields:
1 2 3 4 5 6 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"> <TextView android:id="@+id/tv_img_name" /> <ImageView android:id="@+id/img_view" /> </LinearLayout> |
– ViewHolder
class contains Android UI fields that point to layout items:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class ImgViewHolder extends RecyclerView.ViewHolder { public TextView nameView; public ImageView imageView; public ImgViewHolder(View itemView) { super(itemView); nameView = (TextView) itemView.findViewById(R.id.tv_img_name); imageView = (ImageView) itemView.findViewById(R.id.img_view); } } |
3.2 FirebaseRecyclerAdapter subclass
We need a subclass of the FirebaseRecyclerAdapter
and implement its populateViewHolder()
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private FirebaseRecyclerAdapter<Message, MessageViewHolder> mAdapter; // ... // mDataReference = FirebaseDatabase.getInstance().getReference("images"); Query query = mDataReference.limitToLast(3); mAdapter = new FirebaseRecyclerAdapter<UploadInfo, ImgViewHolder>( UploadInfo.class, R.layout.item_image, ImgViewHolder.class, query) { @Override protected void populateViewHolder(ImgViewHolder viewHolder, UploadInfo model, int position) { viewHolder.nameView.setText(model.name); Picasso.with(StorageActivity.this) .load(model.url) .error(R.drawable.common_google_signin_btn_icon_dark) .into(viewHolder.imageView); } }; |
Now look at these lines of code:
1 2 3 4 |
Query query = mDataReference.limitToLast(3); mAdapter = new FirebaseRecyclerAdapter<UploadInfo, ImgViewHolder>( UploadInfo.class, R.layout.item_image, ImgViewHolder.class, query) |
– We tell FirebaseRecyclerAdapter
object to use UploadInfo.class when reading from the database.
– Each Message will be displayed in a R.layout.item_image
(that has 2 elements: tv_img_name, img_view).
– We indicate class for ViewHolder
– We can just give reference to database node or sort/filter data by using Query
:
1 2 3 4 5 6 7 |
Query query = mDataReference; Query query = mDataReference.orderByKey(); // orderByValue() or orderByChild("...") Query query = mDataReference.limitToLast(8); // limitToFirst(..), startAt(...), endAt(...), equalTo(...) |
FirebaseRecyclerAdapter
will call populateViewHolder()
method for each Model it finds in database. It passes us the Model
and a ViewHolder
.
So what we should do is map the fields from model to the correct UI elements:
1 2 3 4 5 6 7 8 |
@Override protected void populateViewHolder(ImgViewHolder viewHolder, UploadInfo model, int position) { viewHolder.nameView.setText(model.name); Picasso.with(StorageActivity.this) .load(model.url) .error(R.drawable.common_google_signin_btn_icon_dark) .into(viewHolder.imageView); } |
3.3 RecyclerView
Now we set the adapter for RecyclerView
object to provide child views on demand:
1 2 3 4 5 6 7 8 9 10 11 |
private RecyclerView rcvListImg; // ... rcvListImg = (RecyclerView) findViewById(R.id.rcv_list_img); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setReverseLayout(false); rcvListImg.setHasFixedSize(false); rcvListImg.setLayoutManager(layoutManager); // mAdapter = new FirebaseRecyclerAdapter<UploadInfo, ImgViewHolder>(...); rcvListImg.setAdapter(mAdapter); |
Remember to call adapter cleanup()
method to stop listening for changes in the Firebase database:
1 2 3 4 5 6 |
@Override protected void onDestroy() { super.onDestroy(); mAdapter.cleanup(); } |
4. Depedencies
To add Support Library to Android project, open the build.gradle file (project-level).
Make sure that the repositories section includes a maven section with the “https://maven.google.com” endpoint:
1 2 3 4 5 6 7 8 |
allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } |
For build.gradle file (App-level)
1 2 3 4 5 6 7 8 9 10 11 |
dependencies { // ... compile 'com.google.firebase:firebase-auth:11.0.2' compile 'com.google.firebase:firebase-storage:11.0.2' compile 'com.google.firebase:firebase-database:11.0.2' compile 'com.firebaseui:firebase-ui-database:2.1.1' compile 'com.squareup.picasso:picasso:2.5.2' } apply plugin: 'com.google.gms.google-services' |
II. Practice
1. Goal
We will build an Android App that can:
– create Account, sign in/sign out for Firebase Authentication.
– read/write user to Firebase Realtime Database.
(2 lines above come from this Post).
– upload image to Firebase Cloud Storage (from this Post)
– display list of Images using FirebaseUI FirebaseRecyclerAdapter
.
2. Technology
– Gradle 2.3.3
β Android Studio 2.x
β Firebase Android SDK 11.x
– Firebase UI Database 2.1.1
– Picasso 2.5.2
3. Project Structure
LoginActivity is for Authentication, then user can enter StorageActivity to upload Image to Firebase Storage, Image’s information to Firebase Database, and show list of Images.
4. Step by step
4.1 Create Android Project
– Generate new Android Project with package com.javasampleapproach.firebaserealtimedb
.
– build.gradle (project-level):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'com.google.gms:google-services:3.1.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } |
– build.gradle (App-level):
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 |
apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.0" defaultConfig { applicationId "com.javasampleapproach.firebasestorage" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.4.0' compile 'com.google.firebase:firebase-auth:11.0.2' compile 'com.google.firebase:firebase-storage:11.0.2' compile 'com.google.firebase:firebase-database:11.0.2' compile 'com.firebaseui:firebase-ui-database:2.1.1' compile 'com.squareup.picasso:picasso:2.5.2' testCompile 'junit:junit:4.12' } apply plugin: 'com.google.gms.google-services' |
4.2 Create Firebase Project & Add Firebase Config file
– Follow this guide to generate google-services.json file and move it into your Android App root directory. You don’t need to have SHA-1 Key in this example, just leave it blank.
β Make sure that package_name in google-services.json has a correct value according to:
+ applicationId in build.gradle (App-level).
+ package in AndroidManifest.xml.
In this case, it is com.javasampleapproach.firebasestorage
.
4.3 Enable Firebase Auth
Go to Your Firebase Project Console -> Authentication -> SIGN-IN METHOD -> Enable Email/Password.
4.4 Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javasampleapproach.firebasestorage.models; import com.google.firebase.database.IgnoreExtraProperties; @IgnoreExtraProperties public class UploadInfo { public String name; public String url; public UploadInfo() { } public UploadInfo(String name, String url) { this.name = name; this.url= url; } } |
4.5 LoginActivity
To know how to implement Firebase Authentication App Client, please visit:
Firebase Authentication β How to Sign Up, Sign In, Sign Out, Verify Email | Android
In this tutorial, we don’t explain way to authenticate an user again.
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="3"> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:id="@+id/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:gravity="center" android:text="grokonez.com" android:textSize="28sp" /> <TextView android:id="@+id/status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:padding="4dp" android:text="Signed Out" android:textSize="14sp" /> <TextView android:id="@+id/detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:padding="4dp" android:textSize="14sp" tools:text="Firebase User ID: 123456789abc" /> </LinearLayout> <RelativeLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#E0E0E0" android:gravity="center_vertical"> <LinearLayout android:id="@+id/email_password_fields" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingLeft="16dp" android:paddingRight="16dp"> <EditText android:id="@+id/edt_email" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/edt_password" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="Password" android:inputType="textPassword" /> </LinearLayout> <LinearLayout android:id="@+id/email_password_buttons" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/email_password_fields" android:orientation="horizontal" android:paddingLeft="16dp" android:paddingRight="16dp"> <Button android:id="@+id/btn_email_sign_in" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" android:layout_weight="1" android:text="Sign In" /> <Button android:id="@+id/btn_email_create_account" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" android:layout_weight="1" android:text="Create Account" /> </LinearLayout> <LinearLayout android:id="@+id/layout_signed_in_control" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="horizontal" android:paddingLeft="16dp" android:paddingRight="16dp" android:visibility="gone"> <Button android:id="@+id/btn_sign_out" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Sign Out" /> <Button android:id="@+id/btn_test_message" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Test Storage" /> </LinearLayout> </RelativeLayout> </LinearLayout> |
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
package com.javasampleapproach.firebasestorage; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "LoginActivity"; private TextView txtStatus; private TextView txtDetail; private EditText edtEmail; private EditText edtPassword; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); txtStatus = (TextView) findViewById(R.id.status); txtDetail = (TextView) findViewById(R.id.detail); edtEmail = (EditText) findViewById(R.id.edt_email); edtPassword = (EditText) findViewById(R.id.edt_password); findViewById(R.id.btn_email_sign_in).setOnClickListener(this); findViewById(R.id.btn_email_create_account).setOnClickListener(this); findViewById(R.id.btn_sign_out).setOnClickListener(this); findViewById(R.id.btn_test_message).setOnClickListener(this); mAuth = FirebaseAuth.getInstance(); } @Override protected void onStart() { super.onStart(); FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); } @Override public void onClick(View view) { int i = view.getId(); if (i == R.id.btn_email_create_account) { createAccount(edtEmail.getText().toString(), edtPassword.getText().toString()); } else if (i == R.id.btn_email_sign_in) { signIn(edtEmail.getText().toString(), edtPassword.getText().toString()); } else if (i == R.id.btn_sign_out) { signOut(); } else if (i == R.id.btn_test_message) { testStorage(); } } private void createAccount(String email, String password) { Log.e(TAG, "createAccount:" + email); if (!validateForm(email, password)) { return; } mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.e(TAG, "createAccount: Success!"); // update UI with the signed-in user's information FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { Log.e(TAG, "createAccount: Fail!", task.getException()); Toast.makeText(LoginActivity.this, "Authentication failed!", Toast.LENGTH_SHORT).show(); updateUI(null); } } }); } private void signIn(String email, String password) { Log.e(TAG, "signIn:" + email); if (!validateForm(email, password)) { return; } mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.e(TAG, "signIn: Success!"); // update UI with the signed-in user's information FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { Log.e(TAG, "signIn: Fail!", task.getException()); Toast.makeText(LoginActivity.this, "Authentication failed!", Toast.LENGTH_SHORT).show(); updateUI(null); } if (!task.isSuccessful()) { txtStatus.setText("Authentication failed!"); } } }); } private void signOut() { mAuth.signOut(); updateUI(null); } private boolean validateForm(String email, String password) { if (TextUtils.isEmpty(email)) { Toast.makeText(LoginActivity.this, "Enter email address!", Toast.LENGTH_SHORT).show(); return false; } if (TextUtils.isEmpty(password)) { Toast.makeText(LoginActivity.this, "Enter password!", Toast.LENGTH_SHORT).show(); return false; } if (password.length() < 6) { Toast.makeText(LoginActivity.this, "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show(); return false; } return true; } private void updateUI(FirebaseUser user) { if (user != null) { txtStatus.setText("User Email: " + user.getEmail()); txtDetail.setText("Firebase User ID: " + user.getUid()); findViewById(R.id.email_password_buttons).setVisibility(View.GONE); findViewById(R.id.email_password_fields).setVisibility(View.GONE); findViewById(R.id.layout_signed_in_control).setVisibility(View.VISIBLE); } else { txtStatus.setText("Signed Out"); txtDetail.setText(null); findViewById(R.id.email_password_buttons).setVisibility(View.VISIBLE); findViewById(R.id.email_password_fields).setVisibility(View.VISIBLE); findViewById(R.id.layout_signed_in_control).setVisibility(View.GONE); } } private void testStorage() { startActivity(new Intent(this, StorageActivity.class)); } } |
4.6 ViewHolder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="7dp"> <TextView android:id="@+id/tv_img_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:text="Image Name" android:textColor="@android:color/holo_blue_dark" /> <ImageView android:id="@+id/img_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.javasampleapproach.firebasestorage.viewholder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.javasampleapproach.firebasestorage.R; public class ImgViewHolder extends RecyclerView.ViewHolder { public TextView nameView; public ImageView imageView; public ImgViewHolder(View itemView) { super(itemView); nameView = (TextView) itemView.findViewById(R.id.tv_img_name); imageView = (ImageView) itemView.findViewById(R.id.img_view); } } |
4.7 StorageActivity
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingLeft="16dp" android:paddingRight="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="grokonez.com" android:textSize="20sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="3"> <Button android:id="@+id/btn_choose_file" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Choose File" /> <EditText android:id="@+id/edt_file_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:hint="File Name" /> </LinearLayout> <Button android:id="@+id/btn_upload_file" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Upload" /> <android.support.v7.widget.RecyclerView android:id="@+id/rcv_list_img" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:padding="16dp" /> <Button android:id="@+id/btn_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Back" /> </LinearLayout> |
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
package com.javasampleapproach.firebasestorage; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.EditText; import android.widget.Toast; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnPausedListener; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.javasampleapproach.firebasestorage.models.UploadInfo; import com.javasampleapproach.firebasestorage.viewholder.ImgViewHolder; import com.squareup.picasso.Picasso; public class StorageActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "StorageActivity"; //track Choosing Image Intent private static final int CHOOSING_IMAGE_REQUEST = 1234; private EditText edtFileName; private Uri fileUri; private DatabaseReference mDataReference; private StorageReference imageReference; private StorageReference fileRef; private RecyclerView rcvListImg; private FirebaseRecyclerAdapter<UploadInfo, ImgViewHolder> mAdapter; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_storage); edtFileName = (EditText) findViewById(R.id.edt_file_name); rcvListImg = (RecyclerView) findViewById(R.id.rcv_list_img); mDataReference = FirebaseDatabase.getInstance().getReference("images"); imageReference = FirebaseStorage.getInstance().getReference().child("images"); fileRef = null; progressDialog = new ProgressDialog(this); findViewById(R.id.btn_choose_file).setOnClickListener(this); findViewById(R.id.btn_upload_file).setOnClickListener(this); findViewById(R.id.btn_back).setOnClickListener(this); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setReverseLayout(false); rcvListImg.setHasFixedSize(false); rcvListImg.setLayoutManager(layoutManager); Query query = mDataReference.limitToLast(3); mAdapter = new FirebaseRecyclerAdapter<UploadInfo, ImgViewHolder>( UploadInfo.class, R.layout.item_image, ImgViewHolder.class, query) { @Override protected void populateViewHolder(ImgViewHolder viewHolder, UploadInfo model, int position) { viewHolder.nameView.setText(model.name); Picasso.with(StorageActivity.this) .load(model.url) .error(R.drawable.common_google_signin_btn_icon_dark) .into(viewHolder.imageView); } }; rcvListImg.setAdapter(mAdapter); } private void uploadFile() { if (fileUri != null) { String fileName = edtFileName.getText().toString(); if (!validateInputFileName(fileName)) { return; } progressDialog.setTitle("Uploading..."); progressDialog.show(); fileRef = imageReference.child(fileName + "." + getFileExtension(fileUri)); fileRef.putFile(fileUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { progressDialog.dismiss(); String name = taskSnapshot.getMetadata().getName(); String url = taskSnapshot.getDownloadUrl().toString(); Log.e(TAG, "Uri: " + url); Log.e(TAG, "Name: " + name); writeNewImageInfoToDB(name, url); Toast.makeText(StorageActivity.this, "File Uploaded ", Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { progressDialog.dismiss(); Toast.makeText(StorageActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { // progress percentage double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount(); // percentage in progress dialog progressDialog.setMessage("Uploaded " + ((int) progress) + "%..."); } }) .addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() { @Override public void onPaused(UploadTask.TaskSnapshot taskSnapshot) { System.out.println("Upload is paused!"); } }); } else { Toast.makeText(StorageActivity.this, "No File!", Toast.LENGTH_LONG).show(); } } private void writeNewImageInfoToDB(String name, String url) { UploadInfo info = new UploadInfo(name, url); String key = mDataReference.push().getKey(); mDataReference.child(key).setValue(info); } private void showChoosingFile() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), CHOOSING_IMAGE_REQUEST); } @Override protected void onDestroy() { super.onDestroy(); mAdapter.cleanup(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CHOOSING_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { fileUri = data.getData(); } } @Override public void onClick(View view) { int i = view.getId(); if (i == R.id.btn_choose_file) { showChoosingFile(); } else if (i == R.id.btn_upload_file) { uploadFile(); } else if (i == R.id.btn_back) { finish(); } } private String getFileExtension(Uri uri) { ContentResolver contentResolver = getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); return mime.getExtensionFromMimeType(contentResolver.getType(uri)); } private boolean validateInputFileName(String fileName) { if (TextUtils.isEmpty(fileName)) { Toast.makeText(StorageActivity.this, "Enter file name!", Toast.LENGTH_SHORT).show(); return false; } return true; } } |
4.8 Android Manifest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasampleapproach.firebasestorage"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".StorageActivity" /> </application> </manifest> |
4.9 Run & Check result
– Use Android Studio, build and Run your Android App:
– Firebase Console:
+ Storage:
+ Database:
III. Source code
FirebaseStorage-display-list-images
Last updated on July 13, 2018.
A great and very helpfull guide, thanx a lot!!!
π
hello i do not want the upload feature i just need the to load the images already in my firebase storage into my activities is this possible?