Firebase Storage - Upload Files - Kotlin

Let's see how to upload the file to Firebase storage and download the same. Its really easy to upload files to Storage and it supports any type of files. 

Preparing Firebase Console:

(a) Go to https://console.firebase.google.com/





(b) Then click Add Project, a dialog will be prompted. Enter project name and choose country in it and click on Create Project.





(c) Click on Add Firebase to your Android App, another dialog will be prompted. In that, enter package name (SHA-1 and App Nickname are optional) and click Register App.


fire4.png



fire5.png

(d) Then download google_services.json file, by clicking download button and put that file in app's folder.


fire6.png



fire7.png



(e) After that click on Storage on Side tab. Then click on Rules in that page. Make changes as follows:





Code:

project-level gradle:

Add google service in dependencies



buildscript {
    ext.kotlin_version = '1.2.10'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


app-level gradle:

Include dependencies for Firebase Storage and Glide like below:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.developer.firebase"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.firebase:firebase-storage:11.8.0'
    implementation 'com.google.firebase:firebase-auth:11.8.0'
    implementation 'com.github.bumptech.glide:glide:4.4.0'


    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'


}


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

upload_photo.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_margin="15dp"
        android:scaleType="centerCrop"
        android:src="@drawable/default_pic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>

</android.support.constraint.ConstraintLayout>


StorageActivity.kt:

                        Initially, we have to check whether the permission to read external storage has been provided. If not, we have to request it. Once got permission, we can allow user to choose an image from Phone's Gallery.


                        After that, the chosen image should be uploaded to Firebase's Storage. We can add listener for listening upload's progress, and success or failure status. We can show progress to user using that OnProgressListener. Also know that, the progress is measured in chunks of 256KBs. If your file is smaller that that, it fits in one chunk, so the progress will jumps from 0% to 100% in one go.

class StorageActivity : AppCompatActivity() {

    val PERMISSION_REQUEST_CODE = 1001
    val PICK_IMAGE_REQUEST = 900;
    lateinit var filePath : Uri

    @TargetApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.upload_photo)

        image.setOnClickListener {
            when {
                (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) -> {
                    if (ContextCompat.checkSelfPermission(this@StorageActivity, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_REQUEST_CODE)
                    }else{
                        chooseFile()
                    }
                }

                else -> chooseFile()
            }

        }
    }

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

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode){
            PERMISSION_REQUEST_CODE -> {
                if(grantResults.isEmpty() || grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    Toast.makeText(this@StorageActivity, "Oops! Permission Denied!!",Toast.LENGTH_SHORT).show()
                else
                    chooseFile()
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        when (requestCode){
            PICK_IMAGE_REQUEST -> {
                filePath = data!!.getData()
                uploadFile()

            }
        }
    }

    private fun uploadFile() {
        val progress = ProgressDialog(this).apply {
            setTitle("Uploading Picture....")
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            show()
        }

        val data = FirebaseStorage.getInstance()
        var value = 0.0
        var storage = data.getReference().child("mypic.jpg").putFile(filePath)
                .addOnProgressListener { taskSnapshot ->
                    value = (100.0 * taskSnapshot.bytesTransferred) / taskSnapshot.totalByteCount
                    Log.v("value","value=="+value)
                    progress.setMessage("Uploaded.. " + value.toInt() + "%")
                }
                .addOnSuccessListener { taskSnapshot -> progress.dismiss()
                    val uri = taskSnapshot.downloadUrl
                    Log.v("Download File","File.." +uri);

                    Glide.with(this@StorageActivity).load(uri).into(image)
                }
                .addOnFailureListener{
                   exception -> exception.printStackTrace()
                }

    }
}


Run Application:


Once uploaded successfully, You can view that uploaded image in Console.




Comments

Popular posts from this blog

SOAP Client using ksoap2 in Android - Kotlin

RecyclerView with different number of columns using SpanSizeLookup

Using Camera in Android - Kotlin

Databinding in RecyclerView - Android - Kotlin

Map, Location update and AutoComplete Places - Kotlin

Room with LiveData, ViewModel - Android Architecture Components - Kotlin

Stripe Integration in Android - Kotlin

Braintree Integration in Android - Kotlin

Exploring Android Slices - JetPack

Android JetPack - Scheduling Tasks with WorkManager