Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Advance / Firebase Storage Tutorial for Android – Upload Files in Firebase Storage

Firebase Storage Tutorial for Android – Upload Files in Firebase Storage

November 11, 2016 by Belal Khan 30 Comments

Hello guys, welcome to Firebase Storage Tutorial for Android. In this tutorial we are going to learn how you can upload images to firebase storage. Infact not only images you can use this firebase storage android tutorial to upload any kind of file to firebase storage. So lets start our Firebase Storage Tutorial.

Follow Updated Tutorial from this Link
Firebase Storage Example to Upload and Retrieve Images

Contents

  • 1 Firebase Storage Tutorial Video
  • 2 Starting Firebase Storage Tutorial Project
    • 2.1 Creating a new Project
    • 2.2 Adding Firebase Storage
      • 2.2.1 #1 Connect your app to firebase
      • 2.2.2 #2 Adding Firebase Storage
  • 3 Getting a File to Upload
    • 3.1 Creating File Chooser
      • 3.1.1 Creating Layout
      • 3.1.2 Coding File Chooser
      • 3.1.3 Testing File Chooser
  • 4 Uploading Selected Image
    • 4.1 Coding Upload Method
    • 4.2 Changing the Default Rules
    • 4.3 Testing the Upload
    • 4.4 Sharing is Caring:
    • 4.5 Related

Firebase Storage Tutorial Video

You can go through this Firebase Storage Tutorial Video if you don’t like reading text tutorial. The video is covering everything you will find in this post.

But if you are ok with written post then lets move ahead in this Firebase Storage Tutorial.

Starting Firebase Storage Tutorial Project

Creating a new Project

  • As always the first step is creating a new Android Studio Project.
  • So just create a new Android Studio project using an Empty Activity. I created a project named FirebaseStorage.
  • Once your project is loaded, you can add Firebase storage to it.

Adding Firebase Storage

  • With new Android 2.2 it is really easy to integrate firebase. (If you haven’t updated your studio, you should update your Android Studio).
  • To add Firebase Storage, click on Tools -> Firebase

firebase storage

  • An assistant window would open in left with all the firebase features. We have to select Firebase Storage from the list.

firebase storage

  • Now you will see a link saying Upload and Download a File with Firebase Storage click on it.

firebase file upload

  • Now you will see again the same screen we seen in the last Firebase Cloud Messaging Tutorial. You have to do the same things.

#1 Connect your app to firebase

  • Click  on Connect to Firebase. You will see a dialog asking to create a new firebase app or choose an existing one.

connect to firebase project

#2 Adding Firebase Storage

  • Now Click on the second button Add Firebase Storage to Your App. 

firebase storage tutorial

  • Then click on accept changes and firebase storage is added.

firebase storage tutorial

Getting a File to Upload

  • If we need to upload a file, then the first step is getting that file.
  • For this we will create a File Chooser.

Creating File Chooser

  • First we will create layout for our file chooser.

Creating Layout

  • Come inside activity_main.xml and write the following code.

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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.firebasestorage.MainActivity">
 
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <Button
            android:id="@+id/buttonChoose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Choose" />
 
        <Button
            android:id="@+id/buttonUpload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Upload" />
 
    </LinearLayout>
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/linearLayout" />
 
</RelativeLayout>

  • The above xml code will generate the following layout.

firebase storage

  • Now we will code the functionality to the choose button. When we tap the choose button Image Chooser should open. So lets do it.

Coding File Chooser

  • Come inside MainActivity.java, and write the following code.

MainActivity.java
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
package net.simplifiedcoding.firebasestorage;
 
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
import java.io.IOException;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener /*  implementing click listener */ {
    //a constant to track the file chooser intent
    private static final int PICK_IMAGE_REQUEST = 234;
 
    //Buttons
    private Button buttonChoose;
    private Button buttonUpload;
 
    //ImageView
    private ImageView imageView;
 
    //a Uri object to store file path
    private Uri filePath;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //getting views from layout
        buttonChoose = (Button) findViewById(R.id.buttonChoose);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);
 
        imageView = (ImageView) findViewById(R.id.imageView);
 
        //attaching listener
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }
 
    //method to show file chooser
    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
 
    //handling the image chooser activity result
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
 
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    @Override
    public void onClick(View view) {
        //if the clicked button is choose
        if (view == buttonChoose) {
            showFileChooser();
        }
        //if the clicked button is upload
        else if (view == buttonUpload) {
 
        }
    }
}

Testing File Chooser

  • Now you can run your application to check whether the file chooser is working or not.

file chooser activity

  • As you can see it is working absolutely fine. So now we can move ahead to learn the main topic of this Firebase Storage Tutorial, which is uploading a file.

Uploading Selected Image

  • We have the chosen image. Now when the user will tap the upload button the file should be uploaded to Firebase Storage.

Coding Upload Method

  • So inside MainActivity class create a method named uploadFile() and write the following code for it.

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
    //this method will upload the file
    private void uploadFile() {
        //if there is a file to upload
        if (filePath != null) {
            //displaying a progress dialog while upload is going on
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading");
            progressDialog.show();
 
            StorageReference riversRef = storageReference.child("images/pic.jpg");
            riversRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //if the upload is successfull
                            //hiding the progress dialog
                            progressDialog.dismiss();
 
                            //and displaying a success toast
                            Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            //if the upload is not successfull
                            //hiding the progress dialog
                            progressDialog.dismiss();
 
                            //and displaying error message
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //calculating progress percentage
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
 
                            //displaying percentage in progress dialog
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });
        }
        //if there is not any file
        else {
            //you can display an error toast
        }
    }

  • Now call this method when the button upload is clicked.

Java
1
2
3
4
5
6
7
8
9
10
11
    @Override
    public void onClick(View view) {
        //if the clicked button is choose
        if (view == buttonChoose) {
            showFileChooser();
        }
        //if the clicked button is upload
        else if (view == buttonUpload) {
            uploadFile();
        }
    }

  • If you will try running the application it will not work, because of the default Storage Rules.

Changing the Default Rules

  • Because the default rules says, only authenticated users will be able to read or write the Firebase Storage. But we haven’t done any authentication in our application.
  • So for now we are changing the Firebase Storage Rules.
  • So go to Firebase Console and open your Firebase Project. Then from the left menu select Firebase Storage and go to the Rules tab.

firebase storage example

  • You can see I have changed the rule. So you have to change the rule as shown above. Before it was if auth != null but I changed it to if true so the if will always evaluate true.
  • But you should use this only for development purpose. As for production you cannot use this way that anyone can access storage. 

Testing the Upload

  • Now just run your application.

firebase storage upload image

  • You can also check the firebase storage to check whether the file is uploaded or not.

firebase storage uploads

  • As you can see we have the file here in Firebase Storage.
  • If you are facing troubles get my code from the below link.

Firebase Storage Tutorial Source Code

So thats all for this Firebase Storage Tutorial friends. In next post we will learn about creating an image storing application using Firebase Storage. If you are having queries lets meet in comment section. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Advance, Android Application Development Tagged With: firebase storage example, firebase storage tutorial

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Pavel says

    November 11, 2016 at 8:00 pm

    Hello! Thank you for examples.
    I’m trying for example to send your text + image but does not work, here I am asked the question, what am I doing wrong?
    http://stackoverflow.com/questions/40554968/what-does-this-error-loadsystemproperties-persistdebugevent-false-rodebugevent

    Reply
  2. M Hussain says

    November 13, 2016 at 12:04 pm

    Respected Sir, (M Bilal)

    please how to show these all images in listview ……….

    Reply
  3. CK says

    November 15, 2016 at 6:47 am

    How can I upload a pdf or word document to firebase storage?? I have searched all over the internet and I cand find how.

    Reply
    • Ravi says

      January 24, 2017 at 6:10 am

      Hi I am also searching for that video.
      But I am still not able to find any video regarding uploading the pdf files. If you have got one by now plz share or else whenever you get plz revert back.

      Reply
      • Sandy MA says

        February 21, 2017 at 8:06 am

        i have done upload pdf files dude , the main idea is only change this code

        intent.setType(“file.pdf/*”);

        and

        StorageReference riversRef = storageReference.child(“file/.pdf”);
        riversRef.putFile(filePath)

        it will make file folder on console firbase storage

        but i dont know how to upload many files , so i just can upload 1 file 🙁

        Reply
        • Ricki says

          May 12, 2018 at 9:42 am

          Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);

          how about this?

          Reply
  4. Rajesh Satvara says

    December 16, 2016 at 10:29 am

    Show Storage Image in listview not load properly. why ?? i am using Custom(Base) adapter for it.

    Reply
  5. anurag says

    December 16, 2016 at 11:23 am

    hello sir , if we use this code for chat purpose , can we use this code for profile pic ………., if yes how we use upload image as profile pic ….

    Reply
  6. Kushal Rathore says

    December 30, 2016 at 9:30 am

    how can i upload video onto the firebase storage .

    Reply
  7. Rohit says

    January 6, 2017 at 8:44 am

    Sir i have one question
    Can i use firebase in Eclipse IDE if yes than where to add dependance classpath file.

    In Android studio we can add classpath in gradle scripts folder but where in Eclipse.

    Reply
  8. PhanSon says

    January 16, 2017 at 4:41 am

    Help me!
    I edit on rule fire base->read,write:if true;
    But it doesn’t work
    Error is:”an unknown error occurred please check the http result code and inner exception for server response”

    Reply
    • safaa says

      April 6, 2017 at 11:24 pm

      i have also this same . did you find a solution ???

      Reply
  9. Nihar Prabhu says

    February 2, 2017 at 4:28 am

    Sir, what is storageReference.child() ? it is not showing any suggestion and the function is showing the error.

    Reply
    • amit pandya says

      February 8, 2017 at 10:12 am

      i have also this same doubt.

      Reply
      • Sandy Ma says

        February 21, 2017 at 6:45 am

        yeah i got a same problem 🙁

        Reply
        • Disha says

          February 28, 2017 at 1:44 pm

          same doubt 🙁

          Reply
          • Omar says

            March 8, 2017 at 8:20 pm

            Use this , from the decumentation

            FirebaseStorage storage = FirebaseStorage.getInstance();
            StorageReference storageReference = storage.getReference();

    • Zakaria Mansoor says

      June 10, 2017 at 9:11 pm

      that function will create a folder in your firebase main storage folder
      in his case it gonna base /root/images/
      it allows you to create another folder like
      /root/pdfs/
      and so on

      why it gave you error, did you change the rule in your firebase settings as mentioned above ?

      Reply
  10. Boopalan says

    February 14, 2017 at 4:48 am

    Bro is there any way to retrieve images from the firebase in recyclerview if so can you share it??

    Reply
    • Belal Khan says

      February 28, 2017 at 2:34 pm

      Check the updated post here
      https://www.simplifiedcoding.net/firebase-storage-example/

      Reply
  11. SHASHI JAISWAL says

    June 2, 2017 at 4:49 pm

    FOR ERRORS OF This method should only be accessed from tests or within private scope
    use

    @SuppressWarnings (“VisibleForTests”)
    double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();

    Reply
  12. saam says

    June 9, 2017 at 7:21 am

    not proper understand of code

    Reply
  13. Zakaria Mansoor says

    June 10, 2017 at 7:28 pm

    Everything seems working properly, except one thing
    it keeps give me this error :

    StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzbqn: Please sign in before trying to get a token.

    Shall i be signed in using my gmail account in the emulator to get it working ?

    Reply
  14. Yohan says

    July 15, 2017 at 12:59 pm

    Very well done.. and explained.
    But i still feel you should show us how to download that image from Firebase storage when needed.

    I have seen some tutorials with GLIDE, but would like to see your version. Thanx!

    Reply
  15. erlangga87 says

    July 21, 2017 at 4:26 am

    thanks for the tutorial, but why when i click the upload button there is a notification User dont have permission to access this object. Please help me to resolve this problem

    Reply
  16. Subha Pal says

    July 22, 2017 at 9:19 am

    not showing picture in redmi note 3 ……
    bt other device have no problem whyy

    Reply
  17. marzook says

    October 4, 2017 at 7:02 am

    Everything is perfect,but uploading percentage(%) not showing.
    only 0% showing and after upload compleated

    Reply
  18. Vikki says

    November 3, 2017 at 5:37 am

    I want to upload multiple images at a time in bulk

    Reply
  19. Rahul says

    January 26, 2018 at 5:44 pm

    Sir can you tell me how to make an activity which can download pdf files from firebase storage

    Reply
  20. zoom says

    March 9, 2018 at 12:44 pm

    For Those Who are getting Red Lines in Studio After copying this code
    Change This
    StorageReference riversRef = storageReference.child(“images/pic.jpg”);
    to
    StorageReference riversRef =FirebaseStorage.getInstance().getReference().child(“images/pic.jpg”);

    Reply

Leave a Reply to Disha Cancel reply

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

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.