Android : How to upload image on Firebase Storage?


What is Firebase Storage?

Firebase is one of the famous cloud platform service providers of Google which provides services such as Database, storage, hosting and other cloud services for Android, IOS and Web applications. In this article we will specifically take a look at Firebase Storage. How we can use it to upload images from an android device to Firebase Storage.

Implementation of Firebase Storage

We will be creating a simple android application in which we will be simply displaying two buttons and an image view. We will be using one button to pick the image and another button to upload the image to our Firebase Storage. We will be also using an image view in which we will be displaying the image view which is being picked by the user from the device. We will be following a step by step guide to implement a Firebase Storage within our Android application using Kotlin.

Step 1 : Creating a new project in Android Studio

Navigate to Android Studio and click on New Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Kotlin.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.kt file.

Step 2 : Connecting your project to Firebase Storage

Once your project has been created. Navigate to the Tools tab in the Android Studio Toolbar which appears on top of Android Studio. Inside that click on Firebase> Then click on Firebase Storage you will get to see the screen below.

After that you have to simply click on Connect to Firebase to connect your application to Firebase. Then you have to click on Add cloud Storage to Firebase to add Firebase Storage dependencies to it. After clicking on both of these buttons you will get to see below screen.

Now our application has been connected to Firebase Storage.

Step 3 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <!-- creating text view for displaying heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="20dp"
      android:gravity="center"
      android:text="Firebase Storage in Android"
      android:textAlignment="center"
      android:textAllCaps="false"
      android:textColor="#FF000000"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- creating an image view for displaying image-->
   <ImageView
      android:id="@+id/idIVImage"
      android:layout_width="match_parent"
      android:layout_height="300dp"
      android:layout_below="@id/idTVHeading"
      android:layout_margin="10dp"
      android:padding="3dp" />

   <!-- creating a button to choose image-->
   <Button
      android:id="@+id/idBtnChooseImage"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idIVImage"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Choose Image"
      android:textAllCaps="false" />

   <!-- creating a button to upload image-->
   <Button
      android:id="@+id/idBtnUploadImage"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idBtnChooseImage"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Upload Image"
      android:textAllCaps="false" />

</RelativeLayout>

Explanation − In the above code we are creating a root layout as Relative Layout. Inside this layout we are creating a text view to display the heading of the application. After creating this text view we are creating an image view. Inside this image view we will be displaying the image which the user picks from his device. After that we are adding two buttons. One button is used to choose the image from the user device and another button is used to upload the image to Firebase Storage.

Step 4 : Working with MainActivity.kt file

Navigate to app>java>your app’s package name>MainActivity.kt file and add below code to it. Comments are added in the code to get to know in detail.

package com.gtappdevelopers.androidapplication

import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.*

class MainActivity : AppCompatActivity() {
   // creating variable for buttons, image view and Uri for file.
   lateinit var chooseImageBtn: Button
   lateinit var uploadImageBtn: Button
   lateinit var imageView: ImageView
   var fileUri: Uri? = null;

   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      // on below line initializing variables for buttons and image view.
      chooseImageBtn = findViewById(R.id.idBtnChooseImage)
      uploadImageBtn = findViewById(R.id.idBtnUploadImage)
      imageView = findViewById(R.id.idIVImage)

      // on below line adding click listener for our choose image button.
      chooseImageBtn.setOnClickListener {
         // on below line calling intent to get our image from phone storage.
         val intent = Intent()
         // on below line setting type of files which we want to pick in our case we are picking images.
         intent.type = "image/*"
         // on below line we are setting action to get content
         intent.action = Intent.ACTION_GET_CONTENT
         // on below line calling start activity for result to choose image.
         startActivityForResult(
            // on below line creating chooser to choose image.
            Intent.createChooser(
               intent,
               "Pick your image to upload"
            ),
            22
         )
      }

      // on below line adding click listener to upload image.
      uploadImageBtn.setOnClickListener {
         // on below line calling upload image button to upload our image.
         uploadImage()
      }
   }

   // on below line adding on activity result method this method is called when user picks the image.
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
      super.onActivityResult(requestCode, resultCode, data)
      // on below line we are checking if the result is ok
      if (requestCode == 22 && resultCode == RESULT_OK && data != null && data.data != null) {
         // on below line initializing file uri with the data which we get from intent
         fileUri = data.data
         try {
            // on below line getting bitmap for image from file uri.
            val bitmap: Bitmap = MediaStore.Images.Media.getBitmap(contentResolver, fileUri);
            // on below line setting bitmap for our image view.
            imageView.setImageBitmap(bitmap)
         } catch (e: Exception) {
            // handling exception on below line
            e.printStackTrace()
         }
      }
   }

   // on below line creating a function to upload our image.
   fun uploadImage() {
      // on below line checking weather our file uri is null or not.
      if (fileUri != null) {
         // on below line displaying a progress dialog when uploading an image.
         val progressDialog = ProgressDialog(this)
         // on below line setting title and message for our progress dialog and displaying our progress dialog.
         progressDialog.setTitle("Uploading...")
         progressDialog.setMessage("Uploading your image..")
         progressDialog.show()

         // on below line creating a storage refrence for firebase storage and creating a child in it with
         // random uuid.
         val ref: StorageReference = FirebaseStorage.getInstance().getReference()
         .child(UUID.randomUUID().toString())
         // on below line adding a file to our storage.
         ref.putFile(fileUri!!).addOnSuccessListener {
            // this method is called when file is uploaded.
            // in this case we are dismissing our progress dialog and displaying a toast message
            progressDialog.dismiss()
            Toast.makeText(applicationContext, "Image Uploaded..", Toast.LENGTH_SHORT).show()
         }.addOnFailureListener {
            // this method is called when there is failure in file upload.
            // in this case we are dismissing the dialog and displaying toast message
            progressDialog.dismiss()
            Toast.makeText(applicationContext, "Fail to Upload Image..", Toast.LENGTH_SHORT)
            .show()
         }
      }
   }
}

Explanation − In the above code we are firstly creating variables for image view, upload image button, choose image button and a URI variable for our file uri. Then inside our onCreate method we are initializing these variables with their ids which we have specified in our activity_main.xml.

Then we are adding an on click listener for our choose image button. Inside the on click method we are creating a variable for intent, then setting the type for it as images as we want to pick images. Then we are setting the action for it to get the images. After that we are setting start activity for the result to display our image picker. Inside this we are creating an image chooser to choose our image from the user's device.

After that we are creating an onActivityResult method inside which we will be setting the image picked by the user inside our image view. Inside this method firstly we are getting data from our picked image and setting it to our file uri. After that we are creating a bitmap from that file uri and setting that bitmap to our image view to display the selected image inside our image view.

After that we are creating a method to upload image. Inside this method we are checking if the file uri is not null. In that case we are displaying a progress bar on the below line to display progress for image uploading. Inside this progress dialog we are displaying the title, message for this progress dialog. Then on the below line we are creating a storage reference variable to get the reference where we have to upload our image. Inside this reference we are specifying a random uuid to upload our image. After that we are calling the put file method to upload our file to Firebase storage.For this method there are two callbacks one is onSuccessListner. This method is called when our image is uploaded and inside this method we are displaying a toast message and dismissing our progress dialog. Another method is onFailureListner. This method is called when the image upload operation fails. In this case as well we are displaying toast messages and dismissing our progress dialog.

Step 5 : Adding Permissions to AndroidManifest.xml file

Navigate to app>AndroidManifest.xml and add below internet, read storage permissions to it.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 6 : Configuring Firebase Storage on Firebase Console

Navigate to the https://console.firebase.google.com/ to access Firebase Console. Make sure that you are logged in with the same account which you have logged in inside Android Studio. After that you have to navigate to the Build Option in Left pane of the Firebase Console. From that click on Storage to add Firebase Storage for your project. After that you have to simply click on Get started option then you will get to see the screen below.

On this make sure to select Test mode because we are not implementing user authentication for our application. Then simply click on Next to configure Firebase Storage.

Now click on the green color play icon to run your application.

Note − Make sure you are connected to your real device or emulator

Conclusion

In the above tutorial we learn What is Firebase Storage and How we can use it within our android application to store the images within it for storage.

Updated on: 14-Mar-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements