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"?><RelativeLayout   Âandroid:layout_width="match_parent"   Âandroid:layout_height="match_parent"   Âandroid:padding="16dp"   Âtools:context=".MainActivity">ÂÂÂ<!--Linear Layout with horizontal orientation    Âand other properties-->Â<LinearLayout   Âandroid: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-->   Â<Button       Âandroid:id="@+id/btnChoose"       Âandroid:text="Choose"       Âandroid:layout_weight="1"       Âandroid:layout_width="0dp"       Âandroid:layout_height="wrap_content"/>   Â<!--Button for uploading image-->   Â<Button       Âandroid: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-->   Â<ImageView       Âandroid: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.neveropen.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 button   ÂprivateButton btnSelect, btnUpload;   Â// view for image view   ÂprivateImageView imageView;   Â// Uri indicates, where the image will be picked from   ÂprivateUri filePath;   Â// request code   ÂprivatefinalintPICK_IMAGE_REQUEST =22;   Â// instance for firebase storage and StorageReference   ÂFirebaseStorage storage;   ÂStorageReference storageReference;   Â@Override   ÂprotectedvoidonCreate(Bundle savedInstanceState)   Â{       Âsuper.onCreate(savedInstanceState);       ÂsetContentView(R.layout.activity_main);       ÂActionBar actionBar;       ÂactionBar = getSupportActionBar();       ÂColorDrawable colorDrawable           Â=newColorDrawable(               ÂColor.parseColor("#0F9D58"));       ÂactionBar.setBackgroundDrawable(colorDrawable);       Â// initialise views       ÂbtnSelect = findViewById(R.id.btnChoose);       ÂbtnUpload = findViewById(R.id.btnUpload);       ÂimageView = findViewById(R.id.imgView);       Â// get the Firebase storage reference       Âstorage = FirebaseStorage.getInstance();       ÂstorageReference = storage.getReference();       Â// on pressing btnSelect SelectImage() is called       ÂbtnSelect.setOnClickListener(newView.OnClickListener() {           Â@Override           ÂpublicvoidonClick(View v)           Â{               ÂSelectImage();           Â}       Â});       Â// on pressing btnUpload uploadImage() is called       ÂbtnUpload.setOnClickListener(newView.OnClickListener() {           Â@Override           ÂpublicvoidonClick(View v)           Â{               ÂuploadImage();           Â}       Â});   Â}   Â// Select Image method   ÂprivatevoidSelectImage()   Â{       Â// Defining Implicit Intent to mobile gallery       ÂIntent 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   Â@Override   ÂprotectedvoidonActivityResult(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 view       Âif(requestCode == PICK_IMAGE_REQUEST           Â&& resultCode == RESULT_OK           Â&& data !=null           Â&& data.getData() !=null) {           Â// Get the Uri of data           ÂfilePath = data.getData();           Âtry{               Â// Setting image on image view using Bitmap               ÂBitmap bitmap = MediaStore                                   Â.Images                                   Â.Media                                   Â.getBitmap(                                       ÂgetContentResolver(),                                       ÂfilePath);               ÂimageView.setImageBitmap(bitmap);           Â}           Âcatch(IOException e) {               Â// Log the exception               Âe.printStackTrace();           Â}       Â}   Â}   Â// UploadImage method   ÂprivatevoiduploadImage()   Â{       Âif(filePath !=null) {           Â// Code for showing progressDialog while uploading           ÂProgressDialog progressDialog               Â=newProgressDialog(this);           ÂprogressDialog.setTitle("Uploading...");           ÂprogressDialog.show();           Â// Defining the child of storageReference           ÂStorageReference ref               Â= storageReference                     Â.child(                         Â"images/"                         Â+ UUID.randomUUID().toString());           Â// adding listeners on upload           Â// or failure of image           Âref.putFile(filePath)               Â.addOnSuccessListener(                   ÂnewOnSuccessListener<UploadTask.TaskSnapshot>() {                       Â@Override                       ÂpublicvoidonSuccess(                           ÂUploadTask.TaskSnapshot taskSnapshot)                       Â{                           Â// Image uploaded successfully                           Â// Dismiss dialog                           ÂprogressDialog.dismiss();                           ÂToast                               Â.makeText(MainActivity.this,                                         Â"Image Uploaded!!",                                         ÂToast.LENGTH_SHORT)                               Â.show();                       Â}                   Â})               Â.addOnFailureListener(newOnFailureListener() {                   Â@Override                   ÂpublicvoidonFailure(@NonNullException e)                   Â{                       Â// Error, Image not uploaded                       ÂprogressDialog.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                       Â@Override                       ÂpublicvoidonProgress(                           Â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:

