Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application.
This article explains how to build an Android application with the ability to select the image from the mobile gallery and upload images to Firebase Storage.
Here are the detailed steps:
- Step 1. Create a new project on android studio or open an existing project in which you want to add authentication and add the firebase to that android application.
- Step 2. Add the firebase storage dependency in build.gradle (Module:app)file. Latest Dependency for firebase storage is:
implementation 'com.google.firebase:firebase-storage:19.1.0'
- Step 3. Setting up the activity_main.xml layout file
The activity_main.xml layout file consists of:- Two layouts: nesting linear layout inside relative layout
- Two buttons:
- one for selecting an image from gallery
- other button is for uploading an image on firebase storage on the cloud
- An image view in which image is shown chosen from the gallery
Here is complete code for activity_main.xml:
activity_main.xml
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
RelativeLayout
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
android:padding
=
"16dp"
tools:context
=
".MainActivity"
>
<!--Linear Layout with horizontal orientation
and other properties-->
<
LinearLayout
android:id
=
"@+id/layout_button"
android:orientation
=
"horizontal"
android:layout_alignParentTop
=
"true"
android:weightSum
=
"2"
android:layout_width
=
"match_parent"
android:layout_height
=
"wrap_content"
>
<!--Button for choosing image from gallery-->
<
Button
android:id
=
"@+id/btnChoose"
android:text
=
"Choose"
android:layout_weight
=
"1"
android:layout_width
=
"0dp"
android:layout_height
=
"wrap_content"
/>
<!--Button for uploading image-->
<
Button
android:id
=
"@+id/btnUpload"
android:text
=
"Upload"
android:layout_weight
=
"1"
android:layout_width
=
"0dp"
android:layout_height
=
"wrap_content"
/>
</
LinearLayout
>
<!--Image View for showing image chosen from gallery-->
<
ImageView
android:id
=
"@+id/imgView"
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
/>
</
RelativeLayout
>
- Step 4. Setting up MainActivity.java file
In MainActivity- Set listeners on interaction of defined button views. On interaction, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase storage. setOnClickListener is used for that action on interaction.
- When SelectImage method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to search through the device gallery to select the image from the gallery.
- startActivityForResult is used to receive the result, which is the selected image.
- To display this image, make use of a method called onActivityResult(). onActivityResult receives a request code, result code, and the data. Check in this method, if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, display the selected image in the ImageView below buttons.
- Override the startActivityForResult method and write its implementation.
- Also in uploadImage() method, Firebase storage reference is taken and putFile() function is used to upload the image to firebase storage with success and failure listeners. If an image is uploaded than success toast is there otherwise failure toast is there.
MainActivity.java
package
com.neveropen.uploadimagetofirebase;
import
android.app.ProgressDialog;
import
android.content.Intent;
import
android.graphics.Bitmap;
import
android.graphics.Color;
import
android.graphics.drawable.ColorDrawable;
import
android.net.Uri;
import
android.provider.MediaStore;
import
android.support.annotation.Nullable;
import
android.support.v7.app.ActionBar;
import
android.support.v7.app.AppCompatActivity;
import
android.os.Bundle;
import
android.view.View;
import
android.widget.Button;
import
android.widget.ImageView;
import
android.widget.Toast;
import
java.io.IOException;
import
java.util.UUID;
public
class
MainActivity
extends
AppCompatActivity {
// views for button
private
Button btnSelect, btnUpload;
// view for image view
private
ImageView imageView;
// Uri indicates, where the image will be picked from
private
Uri filePath;
// request code
private
final
int
PICK_IMAGE_REQUEST =
22
;
// instance for firebase storage and StorageReference
FirebaseStorage storage;
StorageReference storageReference;
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable
=
new
ColorDrawable(
Color.parseColor(
"#0F9D58"
));
actionBar.setBackgroundDrawable(colorDrawable);
// initialise views
btnSelect = findViewById(R.id.btnChoose);
btnUpload = findViewById(R.id.btnUpload);
imageView = findViewById(R.id.imgView);
// get the Firebase storage reference
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
// on pressing btnSelect SelectImage() is called
btnSelect.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(View v)
{
SelectImage();
}
});
// on pressing btnUpload uploadImage() is called
btnUpload.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(View v)
{
uploadImage();
}
});
}
// Select Image method
private
void
SelectImage()
{
// Defining Implicit Intent to mobile gallery
Intent intent =
new
Intent();
intent.setType(
"image/*"
);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(
intent,
"Select Image from here..."
),
PICK_IMAGE_REQUEST);
}
// Override onActivityResult method
@Override
protected
void
onActivityResult(
int
requestCode,
int
resultCode,
Intent data)
{
super
.onActivityResult(requestCode,
resultCode,
data);
// checking request code and result code
// if request code is PICK_IMAGE_REQUEST and
// resultCode is RESULT_OK
// then set image in the image view
if
(requestCode == PICK_IMAGE_REQUEST
&& resultCode == RESULT_OK
&& data !=
null
&& data.getData() !=
null
) {
// Get the Uri of data
filePath = data.getData();
try
{
// Setting image on image view using Bitmap
Bitmap bitmap = MediaStore
.Images
.Media
.getBitmap(
getContentResolver(),
filePath);
imageView.setImageBitmap(bitmap);
}
catch
(IOException e) {
// Log the exception
e.printStackTrace();
}
}
}
// UploadImage method
private
void
uploadImage()
{
if
(filePath !=
null
) {
// Code for showing progressDialog while uploading
ProgressDialog progressDialog
=
new
ProgressDialog(
this
);
progressDialog.setTitle(
"Uploading..."
);
progressDialog.show();
// Defining the child of storageReference
StorageReference ref
= storageReference
.child(
"images/"
+ UUID.randomUUID().toString());
// adding listeners on upload
// or failure of image
ref.putFile(filePath)
.addOnSuccessListener(
new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public
void
onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
// Image uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast
.makeText(MainActivity.
this
,
"Image Uploaded!!"
,
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(
new
OnFailureListener() {
@Override
public
void
onFailure(
@NonNull
Exception e)
{
// Error, Image not uploaded
progressDialog.dismiss();
Toast
.makeText(MainActivity.
this
,
"Failed "
+ e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
})
.addOnProgressListener(
new
OnProgressListener<UploadTask.TaskSnapshot>() {
// Progress Listener for loading
// percentage on the dialog box
@Override
public
void
onProgress(
UploadTask.TaskSnapshot taskSnapshot)
{
double
progress
= (
100.0
* taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage(
"Uploaded "
+ (
int
)progress +
"%"
);
}
});
}
}
}
Output:
- Main Activity
- Choose image from gallery
- The uploaded image on firebase console: