Firebase Storage – Get List of Files example – Image List | Android

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

firebase-storage-display-list-goal

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:


// 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() {
            @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() {
            @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() {
            @Override
            public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
                // ...
            }
        });

firebase-storage-display-list-demo-storage-console

2. Store images’ information

Use Firebase Realtime Database:


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);
}

firebase-storage-display-list-demo-database-console

3. Display list of Images

3.1 Model and ViewHolder

Model class is a class that represents the data from Firebase:


public class UploadInfo {

    public String name;
    public String url;

    // ...
}

ViewHolder layout (R.layout.item_image) with UI items that correspond to Model fields:

<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:


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:


private FirebaseRecyclerAdapter mAdapter;
// ...
// mDataReference = FirebaseDatabase.getInstance().getReference("images");

Query query = mDataReference.limitToLast(3);

mAdapter = new FirebaseRecyclerAdapter(
        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:


Query query = mDataReference.limitToLast(3);

mAdapter = new FirebaseRecyclerAdapter(
        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:


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:


@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:


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(...);
rcvListImg.setAdapter(mAdapter);

Remember to call adapter cleanup() method to stop listening for changes in the Firebase database:


@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:


allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

For build.gradle file (App-level)


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.

firebase-storage-display-list-demo-app-goal

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

firebase-storage-display-list-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):


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):


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.

firebase-storage-add-app

4.3 Enable Firebase Auth

Go to Your Firebase Project Console -> Authentication -> SIGN-IN METHOD -> Enable Email/Password.

4.4 Model


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.

<?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>

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() {
                    @Override
                    public void onComplete(@NonNull Task 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() {
                    @Override
                    public void onComplete(@NonNull Task 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

<?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>

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

<?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>

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 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.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() {
                        @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() {
                        @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() {
                        @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

<?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-storage-display-list-demo-app-result

- Firebase Console:
+ Storage:
firebase-storage-display-list-demo-storage-console

+ Database:
firebase-storage-display-list-demo-database-console

III. Source code

FirebaseStorage-display-list-images



By grokonez | August 22, 2017.

Last updated on April 23, 2021.



Related Posts


3 thoughts on “Firebase Storage – Get List of Files example – Image List | Android”

  1. Hi ,
    i want to ask i have used two, gridview for the first activity and recylerview for the second. I need help How to show Firebase photos in gridview?
    I have Firebase category contient products. I want to get the image and show them in a gridview.
    My code for moment :

      protected void onStart() {
            super.onStart();
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    categoryEntityList.clear();
                    for (DataSnapshot categorySnapShot : dataSnapshot.getChildren()) {
                        Log.d(TAG, "Outside  : " + categorySnapShot.child("cat_id").getValue());
                        CategoryEntity categoryEntity = new CategoryEntity();
                        categoryEntity.setCat_id(categorySnapShot.child("cat_id").getValue(Long.class));
                        categoryEntity.setCat_name(categorySnapShot.child("cat_name").getValue(String.class));
                      categoryEntity.setCat_image(categorySnapShot.child("cat_image").getValue(String.class));
                        List produitEntityList = new ArrayList();
                        for (DataSnapshot productSnapShot : categorySnapShot.child("products").getChildren()) {
                            ProduitEntity produitEntity = new ProduitEntity();
                            produitEntity.setPd_id(productSnapShot.child("pd_id").getValue(Long.class));
                            produitEntity.setPd_desc(productSnapShot.child("pd_desc").getValue(String.class));
                            produitEntity.setPd_image(productSnapShot.child("pd_image").getValue(String.class));
                            produitEntity.setPd_name(productSnapShot.child("pd_name").getValue(String.class));
                            produitEntity.setPd_prix(productSnapShot.child("pd_prix").getValue(Double.class));
                            produitEntityList.add(produitEntity);
                        }
                        categoryEntity.setProducts(produitEntityList);
                        Log.d(TAG, "Categroy Data  : " + categoryEntity.toString());
                        categoryEntityList.add(categoryEntity);
                    }
                    populateGridView();
                }
    
  2. 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?

Got Something To Say:

Your email address will not be published. Required fields are marked *

*