Android: How to Upload an image on Firebase storage?

Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application.
This article explains how to build an Android application with the ability to select the image from the mobile gallery and upload images to Firebase Storage.
Here are the detailed steps:
- Step 1. Create a new project on android studio or open an existing project in which you want to add authentication and add the firebase to that android application.
- Step 2. Add the firebase storage dependency in build.gradle (Module:app)file. Latest Dependency for firebase storage is:
implementation 'com.google.firebase:firebase-storage:19.1.0'
- Step 3. Setting up the activity_main.xml layout file
The activity_main.xml layout file consists of:- Two layouts: nesting linear layout inside relative layout
- Two buttons:
- one for selecting an image from gallery
- other button is for uploading an image on firebase storage on the cloud
- An image view in which image is shown chosen from the gallery
Here is complete code for activity_main.xml:
activity_main.xml
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:padding="16dp"tools:context=".MainActivity"><!--Linear Layout with horizontal orientationand other properties--><LinearLayoutandroid:id="@+id/layout_button"android:orientation="horizontal"android:layout_alignParentTop="true"android:weightSum="2"android:layout_width="match_parent"android:layout_height="wrap_content"><!--Button for choosing image from gallery--><Buttonandroid:id="@+id/btnChoose"android:text="Choose"android:layout_weight="1"android:layout_width="0dp"android:layout_height="wrap_content"/><!--Button for uploading image--><Buttonandroid:id="@+id/btnUpload"android:text="Upload"android:layout_weight="1"android:layout_width="0dp"android:layout_height="wrap_content"/></LinearLayout><!--Image View for showing image chosen from gallery--><ImageViewandroid:id="@+id/imgView"android:layout_width="match_parent"android:layout_height="match_parent"/></RelativeLayout> - Step 4. Setting up MainActivity.java file
In MainActivity- Set listeners on interaction of defined button views. On interaction, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase storage. setOnClickListener is used for that action on interaction.
- When SelectImage method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to search through the device gallery to select the image from the gallery.
- startActivityForResult is used to receive the result, which is the selected image.
- To display this image, make use of a method called onActivityResult(). onActivityResult receives a request code, result code, and the data. Check in this method, if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, display the selected image in the ImageView below buttons.
- Override the startActivityForResult method and write its implementation.
- Also in uploadImage() method, Firebase storage reference is taken and putFile() function is used to upload the image to firebase storage with success and failure listeners. If an image is uploaded than success toast is there otherwise failure toast is there.
MainActivity.java
packagecom.zambiatek.uploadimagetofirebase;importandroid.app.ProgressDialog;importandroid.content.Intent;importandroid.graphics.Bitmap;importandroid.graphics.Color;importandroid.graphics.drawable.ColorDrawable;importandroid.net.Uri;importandroid.provider.MediaStore;importandroid.support.annotation.Nullable;importandroid.support.v7.app.ActionBar;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.ImageView;importandroid.widget.Toast;importjava.io.IOException;importjava.util.UUID;publicclassMainActivityextendsAppCompatActivity {// views for buttonprivateButton btnSelect, btnUpload;// view for image viewprivateImageView imageView;// Uri indicates, where the image will be picked fromprivateUri filePath;// request codeprivatefinalintPICK_IMAGE_REQUEST =22;// instance for firebase storage and StorageReferenceFirebaseStorage storage;StorageReference storageReference;@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ActionBar actionBar;actionBar = getSupportActionBar();ColorDrawable colorDrawable=newColorDrawable(Color.parseColor("#0F9D58"));actionBar.setBackgroundDrawable(colorDrawable);// initialise viewsbtnSelect = findViewById(R.id.btnChoose);btnUpload = findViewById(R.id.btnUpload);imageView = findViewById(R.id.imgView);// get the Firebase storage referencestorage = FirebaseStorage.getInstance();storageReference = storage.getReference();// on pressing btnSelect SelectImage() is calledbtnSelect.setOnClickListener(newView.OnClickListener() {@OverridepublicvoidonClick(View v){SelectImage();}});// on pressing btnUpload uploadImage() is calledbtnUpload.setOnClickListener(newView.OnClickListener() {@OverridepublicvoidonClick(View v){uploadImage();}});}// Select Image methodprivatevoidSelectImage(){// Defining Implicit Intent to mobile galleryIntent intent =newIntent();intent.setType("image/*");intent.setAction(Intent.ACTION_GET_CONTENT);startActivityForResult(Intent.createChooser(intent,"Select Image from here..."),PICK_IMAGE_REQUEST);}// Override onActivityResult method@OverrideprotectedvoidonActivityResult(intrequestCode,intresultCode,Intent data){super.onActivityResult(requestCode,resultCode,data);// checking request code and result code// if request code is PICK_IMAGE_REQUEST and// resultCode is RESULT_OK// then set image in the image viewif(requestCode == PICK_IMAGE_REQUEST&& resultCode == RESULT_OK&& data !=null&& data.getData() !=null) {// Get the Uri of datafilePath = data.getData();try{// Setting image on image view using BitmapBitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);imageView.setImageBitmap(bitmap);}catch(IOException e) {// Log the exceptione.printStackTrace();}}}// UploadImage methodprivatevoiduploadImage(){if(filePath !=null) {// Code for showing progressDialog while uploadingProgressDialog progressDialog=newProgressDialog(this);progressDialog.setTitle("Uploading...");progressDialog.show();// Defining the child of storageReferenceStorageReference ref= storageReference.child("images/"+ UUID.randomUUID().toString());// adding listeners on upload// or failure of imageref.putFile(filePath).addOnSuccessListener(newOnSuccessListener<UploadTask.TaskSnapshot>() {@OverridepublicvoidonSuccess(UploadTask.TaskSnapshot taskSnapshot){// Image uploaded successfully// Dismiss dialogprogressDialog.dismiss();Toast.makeText(MainActivity.this,"Image Uploaded!!",Toast.LENGTH_SHORT).show();}}).addOnFailureListener(newOnFailureListener() {@OverridepublicvoidonFailure(@NonNullException e){// Error, Image not uploadedprogressDialog.dismiss();Toast.makeText(MainActivity.this,"Failed "+ e.getMessage(),Toast.LENGTH_SHORT).show();}}).addOnProgressListener(newOnProgressListener<UploadTask.TaskSnapshot>() {// Progress Listener for loading// percentage on the dialog box@OverridepublicvoidonProgress(UploadTask.TaskSnapshot taskSnapshot){doubleprogress= (100.0* taskSnapshot.getBytesTransferred()/ taskSnapshot.getTotalByteCount());progressDialog.setMessage("Uploaded "+ (int)progress +"%");}});}}}
Output:
- Main Activity
- Choose image from gallery
- The uploaded image on firebase console:




