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
- Before you can start uploading Image to Firebase, make sure your Android app is connected to Firebase.
- Authentication system is added to your app.
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 the 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 the image in Firebase
- Constraint layout – For building UI
- Picasso – For displaying the 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 the Android Manifest file inside the 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:onClick="selectImage"
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" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:onClick="uploadImage"
android:text="Upload"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button2" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="32dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp"
android:scaleType="centerCrop"
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 the image gets uploaded to Firebase storage inside the images folder. In the next tutorial, I will show you how to add Phone Number Authentication in your Android app using Firebase.