Firebase Storage Example – Uploading and Retrieving Files

In a previous tutorial we learnt about Firebase Storage. But I didn’t cover retrieval of the uploaded files from Firebase Storage. So here is another Firebase Storage Example. In this tutorial we will learn Uploading Files to Firebase Storage and Retrieving Uploaded Files from Firebase Storage. So lets start this Firebase Storage Example.

If you are dealing with PDF Files Follow this Tutorial
Firebase Storage Upload and Download PDF Files

Firebase Storage Example Video Demo

  • You can watch this video to know what we are going to build in this tutorial.

Firebase Storage Example

  • As always the first step is creating a new Android Studio Project.

Creating a New Project

  • I have just created a project named FirebaseUpload.
  • In the project we will be uploading images to Firebase Storage and then we will fetch back the uploaded images to display them into RecyclerView.
  • So now we will setup firebase storage to our project.

Setting Up Firebase Storage and Firebase Database

  • We will upload the images to Firebase Storage and in the Firebase Database we will store the image URL. For this we need to setup both in our project.
  • Go to tools -> firebase

setting firebase

  • Now you will see an Assistant Window, you can setup Firebase Database from here.
firebase database
Firebase Database
  • The same way you can setup Firebase Storage.

firebase storage

Creating Layout

  • Now we need to build the following layout for activity_main.xml.
firebase storage example
activity_main.xml
  • We have the following components in the above layout.
    Choose Button: We will tap this button to choose an image from the gallery.
    EditText Enter Name: In this EditText we will put the label for the chosen image.
    ImageView: The middle area (you cann’t see it in the layout because it is blank ImageView) contains an ImageView where we will display the chosen image.
    Upload Button: Tapping this button will upload the selected image to Firebase Storage.
    TextView Uploads: Tapping this TextView will open another activity where we will display the uploaded images with labels.
  • You can use the following xml code to build the above layout.

Defining Firebase Constants

  • Create a java class named Constants.java and define the following.

Defining View Objects and Constants

  • Come inside MainActivity.java and define the following objects and constants.

  • Now inside onCreate() we will initialize the the objects and attach click listeners.

Adding File Chooser

  • Define a new method showFileChooser().

  • Now we need to handle the Intent result. For this we will override the method onActivityResult().

  • Now we will call the method showFileChooser() when the choose image button is clicked. For this come inside the overriden method onClick() and write the following code.

  • Now try running the application and you will see that choose image is working fine.

choose image

  • Now we will code the upload functionality.

Uploading File to Firebase Storage and Saving URL to Firebase Database

Building Database Model

  • First we will create a class to store the Image data to Firebase Database. So create a class named Upload.java.

Getting Selected File Extension

  • We will rename the file to a unique name as if we upload the file with same name then files would be overwritten. So after renaming the file the extension should remain the same. So inside MainActivity.java create a method getFileExtension() and it will return as the extension of the selected file by taking Uri object.

Uploading the File to Firebase Storage

  • Now we will create a method inside MainActivity.java that will upload the selected file to Firebase Storage. So create a method name uploadFile() and write the following code.

  • Now we need to call this method on Upload Button Click. So modify onClick() method as below.

  • Now try running your application and upload will work.

firebase storage upload

Retrieving Files from Firebase Storage

  • Now we will create a new activity where we display all the uploaded images with labels.
  • So create a new activity named ShowImagesActivity and inside the layout file of this activity we will create a RecyclerView.

Adding RecyclerView and CardView

  • First we need to add dependencies for RecyclerView and CardView.
  • Go to File -> Project Structure and go to dependencies tab. Here click on plus icon and select Library dependency.

adding recyclerview

  • Now here you need to find and add RecyclerView and CardView.

adding recyclerview

  • Now sync your project.

Adding Glide

  • We also need to add Glide Library. As we need to fetch images from the URL and for this I will be using Glide Library.
  • So just modify  dependencies block of your app level build.gradle file as below.

  • Now sync the project with gradle.

Creating RecyclerView Layout

  • Now we will design the layout for our RecyclerView. It will contain an ImageView and a TextView inside a CardView. So create a new layout resource file named layout_images.xml.

  • So our layout for RecyclerView is ready. Now we will create an Adapter.

Creating RecyclerView Adapter

  • Create a class named MyAdapter.java and write the following code.

  • Now come inside layout file of this ShowImagesActivity and add a RecyclerView.

  • Now write the following code inside ShowImagesActivity.java

  • Thats it now just run your application and you will see all the fetched images in the next activity.

firebase storage example

  • Bingo! Its working absolutely fine.  Now if you are having troubles or confusions you can get my source code from the link given below.

So thats it for Firebase Storage Example. If you are facing problems then let me know in the comment section and I will try to help you out. Also don’t forget to share this Firebase Storage Example  if you found it useful. Thank You 🙂

88 thoughts on “Firebase Storage Example – Uploading and Retrieving Files”

  1. Hello,
    You didn’t handle READ_EXTERNAL_STORAGE, this permission is considered a dangerous permission and runtime permission should be handled,
    Am i missing something here?

    Thanks

    Reply
    • This could help;
      Under your class line
      -public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 2017;
      and check this method in “onCreate”
      -if (!checkAndRequestPermissions()) {
      return;
      }
      here is multiple request permission method,
      private boolean checkAndRequestPermissions() {
      int permissionINTERNET = ContextCompat.checkSelfPermission(this, android.Manifest.permission.INTERNET);
      int permissionACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_NETWORK_STATE);
      int permissionREAD_EXTERNAL_STORAGE = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
      int permissionWRITE_EXTERNAL_STORAGE = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
      List listPermissionsNeeded = new ArrayList();
      if (permissionINTERNET != PackageManager.PERMISSION_GRANTED) {
      listPermissionsNeeded.add(android.Manifest.permission.INTERNET);
      }
      if (permissionACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) {
      listPermissionsNeeded.add(android.Manifest.permission.ACCESS_NETWORK_STATE);
      }
      if (permissionREAD_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
      listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
      }
      if (permissionWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
      listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
      }
      if (!listPermissionsNeeded.isEmpty()) {
      ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
      return false;
      }
      return true;
      }
      hope this help. 🙂

      Reply
    • bro go to storage section. then select rules tab. there you will see instructions to enable API and a link for this purpose will be given in these instructions. Go and just follow link.and after this, again go to rule tab of storage just make little amendment i.e. replace != with ==

      Reply
  2. i got error on Tasksnapshot , taskSnapshot.getDownloadUrl().toString());

    i give permission to write external storage too…

    it show “This method should only be accessed from tests or within private scope less… (Ctrl+F1)
    This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations. Examples of errors flagged by this inspection:
    Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen).
    Forgetting to invoke the overridden method (via super) in methods that require it
    Calling a method that requires a permission without having declared that permission in the manifest
    Passing a resource color reference to a method which expects an RGB integer value.
    …and many more”

    Reply
  3. The images are not displaying when i click view upload button. i have already include all the libraries. Still it is not working. please help

    Reply
    • Sorry for bothering, I tried to make delete function like this:
      private boolean deleteImage(String id) {
      DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS).child(id);
      // Delete the file
      mDatabase.removeValue();
      // announcement that image deleted.
      Toast.makeText(getApplicationContext(), “Image Deleted”, Toast.LENGTH_LONG).show();
      return true;
      }
      But not succeed, how can I do this?

      Reply
  4. Hello,
    This is a nice tutorial. I got this error while adding the realtime database to my app
    Error:(28, 13) Failed to resolve: com.google.firebase:firebase-auth:9.2.1
    you can help me

    Reply
  5. I got an error

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ri.cesic/com.example.ri.cesic.UploadActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference

    What is wrong?

    Reply
  6. when I click upload button it shows me the users does not have permission to access this project. can anyone tell me to resolve this.

    Reply
  7. Hello,

    In the last activity (ShowImagesActivity.java), in the line:

    mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);

    the parameter –> Constants.DATABASE_PATH_UPLOADS is throwing error. Please help. All the dependencies and the files are added properly and manifest is also updated.

    Reply
  8. I am getting the folowing error:

    java.lang.NullPointerException: Attempt to invoke interface method ‘int java.util.List.size()’ on a null object reference
    at com.example.anurag_g01.secretspace.UploadImageAdapter.getItemCount(UploadImageAdapter.java:50)

    Reply
  9. Belal, i need help in a code, I have several data in the firebase database, a latitude and a longitude in the children, I want to retrieve all this data and add bookmarks in Google Maps in the app. I made this code below and it is giving error. What did I do wrong?

    public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

    ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    if (dataSnapshot.exists()) {
    double latitude = dataSnapshot.child(“latitude”).getValue(Double.class);
    double longitude = dataSnapshot.child(“longitude”).getValue(Double.class);
    LatLng local = new LatLng(latitude, longitude);
    mMap.addMarker(new MarkerOptions().position(local).title(“New Marker”));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(local,18));
    } else {
    Log.e(TAG, “onDataChange: No data”);
    }

    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
    throw databaseError.toException();
    }
    });

    Reply
  10. Hi, thanks for tutorial it works great :)) Can I make the same app with videos ? I change intent.setType but it’s only affects uploading as I understand. How can I retrieve videos and see them in recyclerview??

    Reply
  11. hai, this is great tutorial
    i want to ask a question. How to sort it with the lastest upload?

    i mean, in the view uploads, how can we show the newest uploaded images on the top? when i try to upload a new images it will be on the bottom of the list.

    thanks for that

    Reply
  12. i click choose button and selecting an image from gallery but the image is not displayed in image view.and when i click upload it shows unknown error occurred

    Reply
  13. Hi
    I am vijay, from this tutorial when i show image and text on another activity then it show “permission denied”.
    please help me.

    Reply
  14. Thank you for the tutorial everything works fine. if i manually upload a file using the firebase console and then click on view to see the images on the firebase it only shows images that i have uploaded from my own phone. not the one present on the firebase storage.

    Reply
  15. I have a question.How we can retrieve specific images from firebase storage by providing some parameters.
    Like i say i only need those images whose name is XYZ.

    Reply
  16. Really Nice And Informative tutorial God Bless!!! Please just one more request could be greatly appreciated which is how to download the image back to our internal storage. Thanks

    Reply
  17. This code upload image and save its URL in firebase Database pls use it ..

    private void uploadFile1() {
    if (filePath != null) {
    progressDialog = new ProgressDialog( this );
    progressDialog.setTitle( “Uploading..” );
    progressDialog.show();
    final StorageReference storageFileAddress = storageReference.child( Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + “.” + getFileExtension( filePath ) );
    storageFileAddress.putFile( filePath )
    .addOnSuccessListener( new OnSuccessListener() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    //dismissing the progress dialog
    progressDialog.dismiss();
    storageFileAddress.getDownloadUrl().addOnSuccessListener( new OnSuccessListener() {
    @Override
    public void onSuccess(Uri uri) {
    Upload upload = new Upload( editTextName.getText().toString().trim(), uri.toString() );
    String uploadId = mDatabase.push().getKey();
    mDatabase.child( uploadId ).setValue( upload );
    }
    } );
    }
    } )
    .addOnFailureListener( new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
    progressDialog.dismiss();
    Toast.makeText( getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG ).show();
    }
    } )
    .addOnProgressListener( new OnProgressListener() {
    @Override
    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
    //displaying the upload progress
    double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
    progressDialog.setMessage( “Uploaded ” + ((int) progress) + “%…” );
    }
    } );

    } else {
    //display an error if no file is selected
    }
    }

    Reply
  18. taskSnapshot.getDownloadUrl().toString());

    sir at .getDownloadUrl() giving error i replace it with getUploadSessionUri() but in can’t uploading image. giving an unknown error

    Reply
  19. Please help me I m getting error while displaying the images in recycler view and I have checked permission project and also firebase console.

    W/SyncTree: Listen at /uploads failed: DatabaseError: Permission denied

    Reply
  20. Thank you Brother, I like your kotlin android videos. Just now I learned firebase kotlin from your video. I am requesting you to make a firestore kotlin video from step by step. I am getting any video for that in the internet. If I got also they are not explaining from step by step like you.

    Reply
  21. My viewUploadImage is not working— i mean when i click on view uploads no action is performed what the reason behind it.

    Reply
  22. please check the http result code and inner exception for server response
    m getting this while m upload the file pls help

    Reply
  23. Thank you for the tutorial with code. all the working properly but the picture is not retrieving from the firebase but the name is retrieving perfectly.
    Can you please provide me a help

    Reply
  24. hi my recycler view doesnot sgow images it just show height and width with nme of recycler view but images are not showing in it.plese hhelp me ASAP

    Reply
  25. In my project when i click on upload button then loading is continuesly running.image are not completely upload and progressbar only 0% show

    Reply
  26. Sir, may I know how to pass data value from another activity to MyAdapter.java? Because I need to do some calculation and display in the adapter. It was appreciated if sir could help me. Thank you very much

    Reply
  27. My image is uploading properly but I can’t retrieve the image from the database. Only the text is coming. Can you please help me out.

    Reply

Leave a Comment