How to Upload Image to Firebase Storage in Android Studio using Kotlin

Last updated Jan 24, 2022

In this android firebase tutorial we will see how to upload image to firebase storage in Android Studio using Kotlin language.Cloud Storage for Firebase is a Google-scaled object storage service that is powerful, easy, and cost-effective. The Firebase SDKs for Cloud Storage provide Google security for file uploads and downloads for your Firebase apps, regardless of network conditions.
 

Implementation of Upload Image:

Step 1.
Create a new Project in android studio.

Go to File > New > New Project > Firebase Upload Image Kotlin > Next > Enter Name > Select Language Kotlin > Finish.

 

After creating the new project, Android Studio starts Gradle and builds your project, which may take a few seconds.
 

Step 2.  Integrate the app with firebase:

We will add the project to firebase manually:

Go to Firebase console:

https://console.firebase.google.com/

 

Click on Add Project (+) and enter the project name then click Continue:

Upload Image to Firebase Storage Server Android kotliin

 

You will see this screen after continue and click Continue Again:

Upload Image to Firebase Storage Server Android kotliin 2

 

You will land to this screen that will ask for Choose or create a Google Ananlytics Account and  click on drag drop and choose the 'Default Account for Firebase' and then click  'Create Project'.

Upload Image to Firebase Storage Server Android kotliin 3


You will see please wait screen and you will get a message "Your new project is ready" and click to Continue.

Upload Image to Firebase Storage Server Android kotliin 4

 

You will redirect to the project dashboard, Here you will  add a android app:

Upload Image to Firebase Storage Server Android kotliin 5



Choose Android Option like in above image and add the following information:
 

1. Register App
Enter you package name, you will get your package name -> Open AndroidManifest.xml file , there you will package = "com.example.packageName" under manifest tag.

Upload Image to Firebase Storage Server Android kotliin 6

Click on  Register App.
 

2. Download Confige File
       Download google-Services.json file and click on Next.

3. Add Firebase SDK 

       Click next, without changing anything.

4. Final click on Continue to Console.
 

 

Step 3. Now we will add the downloaded google-services.json file to the app.

Copy the google-services.json file and paste inside:

FirebaseOtpLogin > app > right-click > paste.

 

Your structure be like: 

Upload Image to Firebase Storage Server Android kotliin 7


 

Step 4. Add the internet permission to AndroidManifest.xml file above application tag

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

 

Step 5. Open project level gradle file (build.gradle(project)) and add the following inside dependencies

classpath 'com.google.gms:google-services:4.3.10'

 

Step 6. Now go to build.gradle(app) file 
Add the firebase storage dependency inside dependencies

implementation 'com.google.firebase:firebase-storage-ktx:20.0.0'
implementation 'com.google.firebase:firebase-firestore-ktx:24.0.0'

 

Apply google-services plugin in the bottom of file:

apply plugin: 'com.google.gms.google-services'

Click Sync Now to continue.
 

Step 7. Now go to activity_main.xml and add the following layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity"
    android:padding="30dp"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/image_preview"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:background="@color/purple_700"
        />

    <Button
        android:id="@+id/btn_choose_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Choose image"
        />

    <Button
        android:id="@+id/btn_upload_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload image"
        />

</LinearLayout>

 

The Layout will give you given appearance:

Upload Image to Firebase Storage Server Android kotliin 8

 

Step 8. Go to MainActivity.kt file and add the following code:

Create variables

    private val PICK_IMAGE_REQUEST = 71
    private var filePath: Uri? = null
    private var firebaseStore: FirebaseStorage? = null
    private var storageReference: StorageReference? = null
    lateinit var imagePreview: ImageView
    lateinit var btn_choose_image: Button
    lateinit var btn_upload_image: Button

 

Initialize variables below setContentView(R.layout.activity_main).

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_choose_image = findViewById(R.id.btn_choose_image)
        btn_upload_image = findViewById(R.id.btn_upload_image)
        imagePreview = findViewById(R.id.image_preview)

        firebaseStore = FirebaseStorage.getInstance()
        storageReference = FirebaseStorage.getInstance().reference

    }

 

Set click listener on upload and choose button

 btn_choose_image.setOnClickListener { launchGallery() }
 btn_upload_image.setOnClickListener { uploadImage() }

 

Create a new function launchGallery for Choose image from gallery

private fun launchGallery() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
    }

 

Override a function onActivityResult()

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
            if(data == null || data.data == null){
                return
            }

            filePath = data.data
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, filePath)
                imagePreview.setImageBitmap(bitmap)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

 

Create new function for UploadImage()

private fun uploadImage(){
        if(filePath != null){
            val ref = storageReference?.child("myImages/" + UUID.randomUUID().toString())
            val uploadTask = ref?.putFile(filePath!!)
            
        }else{
            Toast.makeText(this, "Please Upload an Image", Toast.LENGTH_SHORT).show()
        }
    }

 

The Complete code of  MainActivity.kt file:

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.Task
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import java.io.IOException
import java.util.*
import kotlin.collections.HashMap

class MainActivity : AppCompatActivity() {

    private val PICK_IMAGE_REQUEST = 71
    private var filePath: Uri? = null
    private var firebaseStore: FirebaseStorage? = null
    private var storageReference: StorageReference? = null
    lateinit var imagePreview: ImageView
    lateinit var btn_choose_image: Button
    lateinit var btn_upload_image: Button


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_choose_image = findViewById(R.id.btn_choose_image)
        btn_upload_image = findViewById(R.id.btn_upload_image)
        imagePreview = findViewById(R.id.image_preview)

        firebaseStore = FirebaseStorage.getInstance()
        storageReference = FirebaseStorage.getInstance().reference

        btn_choose_image.setOnClickListener { launchGallery() }
        btn_upload_image.setOnClickListener { uploadImage() }
    }

    private fun launchGallery() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
            if(data == null || data.data == null){
                return
            }

            filePath = data.data
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, filePath)
                imagePreview.setImageBitmap(bitmap)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    private fun uploadImage(){
        if(filePath != null){
            val ref = storageReference?.child("myImages/" + UUID.randomUUID().toString())
            val uploadTask = ref?.putFile(filePath!!)

        }else{
            Toast.makeText(this, "Please Upload an Image", Toast.LENGTH_SHORT).show()
        }
    }

}

 

Step 9. Before run your project please follow these steps:

In your firebase project console, go to Storage and Click on Get Started

Upload Image to Firebase Storage Server Android kotliin 9


Then choose Start in Production and Click Next.

Go to Rules > change your rules:

Upload Image to Firebase Storage Server Android kotliin 10

 

Step 10. Finally run your app and you will get following output.

OUTPUT:

Choose Image and set on ImageView

Upload Image to Firebase Storage Server Android kotliin 11

 

After click on Upload Image, the storage be like:

Upload Image to Firebase Storage Server Android kotliin 12


Inside myImages folder in Firebase Storage:

Upload Image to Firebase Storage Server Android kotliin 13

 

Note: If your image will not uploaded please add your SHA Keys to firebase project by following:

 

Get SHA keys by following these steps given below and click enter :

 

Upload Image to Firebase Storage Server Android kotliin 14

 

And your keys be like: 

Upload Image to Firebase Storage Server Android kotliin 15

 

On the Firebase console go to Project Overview ->  Project Setting, and click add fingerprint button, and add your SHA keys copied from firebase

Upload Image to Firebase Storage Server Android kotliin 16

and download the google-services.json file and follow the step no. 3.
 

Conclusion: In this article, we covered how to upload image to  firebase storage in Android Studio using Kotlin language.

 

Download Source code

 

Related

Firebase Mobile number authentication in Android with kotlin code

Firebase FCM Pushnotifications with Android

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity"
    android:padding="30dp"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/image_preview"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:background="@color/purple_700"
        />

    <Button
        android:id="@+id/btn_choose_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Choose image"
        />

    <Button
        android:id="@+id/btn_upload_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload image"
        />

</LinearLayout>

 

The Layout will give you given appearance:

Upload Image to Firebase Storage Server Android kotliin 8

 

Step 8. Go to MainActivity.kt file and add the following code:

Create variables

    private val PICK_IMAGE_REQUEST = 71
    private var filePath: Uri? = null
    private var firebaseStore: FirebaseStorage? = null
    private var storageReference: StorageReference? = null
    lateinit var imagePreview: ImageView
    lateinit var btn_choose_image: Button
    lateinit var btn_upload_image: Button

 

Initialize variables below setContentView(R.layout.activity_main).

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_choose_image = findViewById(R.id.btn_choose_image)
        btn_upload_image = findViewById(R.id.btn_upload_image)
        imagePreview = findViewById(R.id.image_preview)

        firebaseStore = FirebaseStorage.getInstance()
        storageReference = FirebaseStorage.getInstance().reference

    }

 

Set click listener on upload and choose button

 btn_choose_image.setOnClickListener { launchGallery() }
 btn_upload_image.setOnClickListener { uploadImage() }

 

Create a new function launchGallery for Choose image from gallery

private fun launchGallery() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
    }

 

Override a function onActivityResult()

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
            if(data == null || data.data == null){
                return
            }

            filePath = data.data
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, filePath)
                imagePreview.setImageBitmap(bitmap)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

 

Create new function for UploadImage()

private fun uploadImage(){
        if(filePath != null){
            val ref = storageReference?.child("myImages/" + UUID.randomUUID().toString())
            val uploadTask = ref?.putFile(filePath!!)
            
        }else{
            Toast.makeText(this, "Please Upload an Image", Toast.LENGTH_SHORT).show()
        }
    }

 

The Complete code of  MainActivity.kt file:

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.Task
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import java.io.IOException
import java.util.*
import kotlin.collections.HashMap

class MainActivity : AppCompatActivity() {

    private val PICK_IMAGE_REQUEST = 71
    private var filePath: Uri? = null
    private var firebaseStore: FirebaseStorage? = null
    private var storageReference: StorageReference? = null
    lateinit var imagePreview: ImageView
    lateinit var btn_choose_image: Button
    lateinit var btn_upload_image: Button


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_choose_image = findViewById(R.id.btn_choose_image)
        btn_upload_image = findViewById(R.id.btn_upload_image)
        imagePreview = findViewById(R.id.image_preview)

        firebaseStore = FirebaseStorage.getInstance()
        storageReference = FirebaseStorage.getInstance().reference

        btn_choose_image.setOnClickListener { launchGallery() }
        btn_upload_image.setOnClickListener { uploadImage() }
    }

    private fun launchGallery() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
            if(data == null || data.data == null){
                return
            }

            filePath = data.data
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, filePath)
                imagePreview.setImageBitmap(bitmap)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    private fun uploadImage(){
        if(filePath != null){
            val ref = storageReference?.child("myImages/" + UUID.randomUUID().toString())
            val uploadTask = ref?.putFile(filePath!!)

        }else{
            Toast.makeText(this, "Please Upload an Image", Toast.LENGTH_SHORT).show()
        }
    }

}

 

Step 9. Before run your project please follow these steps:

In your firebase project console, go to Storage and Click on Get Started

Upload Image to Firebase Storage Server Android kotliin 9


Then choose Start in Production and Click Next.

Go to Rules > change your rules:

Upload Image to Firebase Storage Server Android kotliin 10

 

Step 10. Finally run your app and you will get following output.

OUTPUT:

Choose Image and set on ImageView

Upload Image to Firebase Storage Server Android kotliin 11

 

After click on Upload Image, the storage be like:

Upload Image to Firebase Storage Server Android kotliin 12


Inside myImages folder in Firebase Storage:

Upload Image to Firebase Storage Server Android kotliin 13

 

Note: If your image will not uploaded please add your SHA Keys to firebase project by following:

 

Get SHA keys by following these steps given below and click enter :

 

Upload Image to Firebase Storage Server Android kotliin 14

 

And your keys be like: 

Upload Image to Firebase Storage Server Android kotliin 15

 

On the Firebase console go to Project Overview ->  Project Setting, and click add fingerprint button, and add your SHA keys copied from firebase

Upload Image to Firebase Storage Server Android kotliin 16

and download the google-services.json file and follow the step no. 3.
 

Conclusion: In this article, we covered how to upload image to  firebase storage in Android Studio using Kotlin language.

 

Download Source code

 

Related

Firebase Mobile number authentication in Android with kotlin code

Firebase FCM Pushnotifications with Android

-->
Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

4404 Views