In the last tutorial, I showed you how to save and retrieve data from Firebase in Android. Today, I am going to show you how to upload an image to Firebase storage and then show that uploaded image in an ImageView in Android.

The prerequisites 

If you don’t want to add authentication to your app now and plan to add it later, you can change the Firebase storage rules to public so that you can access Firebase storage for uploading Image. For this, go to Firebase console and select your project. Now, click on Storage and then select RULES tab. Replace the line allow read, write: if request.auth != null; with allow read, write;

 

Uploading Image to Firebase and showing it in ImageView

Following dependencies are needed in our project:

  • Firebase Storage – For storing image in Firebase
  • Constraint layout – For building UI
  • Picasso – For displaying image in ImageView from Firebase

So add the below dependencies in your build.gradle file.

//firebase storage
compile 'com.google.firebase:firebase-storage:10.2.0'

//constraint layout
compile 'com.android.support.constraint:constraint-layout:1.0.2'

//picasso
compile 'com.squareup.picasso:picasso:2.5.2'

In order for Picasso to work properly, add the below rule to proguard-rules.pro file.

-dontwarn com.squareup.okhttp.**

Now, Add the Internet permission in your Android Manifest file.

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

Also, add the UploadActivity.java to Android Manifest file inside application tag as shown below.

<application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:theme="@style/AppTheme">
       
       <activity android:name=".UploadActivity"
           />
</application>

Finally, create activity_upload.xml and add the below code.

activity_upload.xml

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

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:text="Select Image"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        android:onClick="selectImage"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="32dp" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:text="Upload"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2"
        android:onClick="uploadImage"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3" />
    
</android.support.constraint.ConstraintLayout>

 

Also, create UploadActivity.java and add the below code.

UploadActivity.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnPausedListener;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

public class UploadActivity extends AppCompatActivity {

    private static final int SELECT_PHOTO = 100;
    Uri selectedImage;
    FirebaseStorage storage;
    StorageReference storageRef,imageRef;
    ProgressDialog progressDialog;
    UploadTask uploadTask;
    ImageView imageView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);

        imageView = (ImageView) findViewById(R.id.imageView2);

        //accessing the firebase storage
         storage = FirebaseStorage.getInstance();

        //creates a storage reference
        storageRef = storage.getReference();


    }

    public void selectImage(View view) {

        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {

                    Toast.makeText(UploadActivity.this,"Image selected, click on upload button",Toast.LENGTH_SHORT).show();
                     selectedImage = imageReturnedIntent.getData();
                }
        }
    }

    public void uploadImage(View view) {

        //create reference to images folder and assing a name to the file that will be uploaded
        imageRef = storageRef.child("images/"+selectedImage.getLastPathSegment());

        //creating and showing progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMax(100);
        progressDialog.setMessage("Uploading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
        progressDialog.setCancelable(false);

        //starting upload
        uploadTask = imageRef.putFile(selectedImage);

        // Observe state change events such as progress, pause, and resume
        uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();

                //sets and increments value of progressbar
                progressDialog.incrementProgressBy((int) progress);

            }
        });

        // Register observers to listen for when the download is done or if it fails
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {

                // Handle unsuccessful uploads
                Toast.makeText(UploadActivity.this,"Error in uploading!",Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();

            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                Toast.makeText(UploadActivity.this,"Upload successful",Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();

                //showing the uploaded image in ImageView using the download url
                Picasso.with(UploadActivity.this).load(downloadUrl).into(imageView);

            }
        });


    }
}

Now when you run the app and upload the Image to Firebase, you will see that image gets uploaded to Firebase storage inside images folder. In the next tutorial, I will show you how to add Phone Number Authentication in your Android app using Firebase.

Related Posts

Android

Add Shimmer Effect to Android app

Rather than the same old circular loader, you can add shimmer effect to Android app when it is loading. This tutorial shows how you can add shimmer effect to your Android app.

Android

Add Phone Number Authentication in Android (Firebase Tutorial #5)

This tutorial shows how to add Phone Number Authentication in Android app using Firebase. We have used FirebaseUI library for achieving authentication.

Android

Save and Retrieve data from Firebase in Android (Firebase Tutorial #3)

This tutorial shows a step by step guide on how to save and retrieve data in Firebase Realtime Database using an Android app.

%d bloggers like this: