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.
Firebase Storage Example to Upload and Retrieve Images
Table of Contents
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
- An assistant window would open in left with all the firebase features. We have to select Firebase Storage from the list.
- Now you will see a link saying Upload and Download a File with Firebase Storage click on it.
- 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.
#2Â Adding Firebase Storage
- Now Click on the second button Add Firebase Storage to Your App.Â
- Then click on accept changes and firebase storage is added.
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.
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 |
<?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.
- 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.
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 |
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.
- 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 50 51 |
//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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@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.
- 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.
- You can also check the firebase storage to check whether the file is uploaded or not.
- As you can see we have the file here in Firebase Storage.
- If you are facing troubles get my code from the below link.
[sociallocker id=1372] Firebase Storage Tutorial Source Code [/sociallocker]
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 🙂