In this tutorial you will learn to upload image to firebase storage in android.
Firebase storage provides facility to upload any file like image, video, audio, etc without using server side code.
Lets quickly learn how we can implement this in android.
Also Read: Android Push Notification Using Firebase Cloud Messaging (FCM)
Android Upload Image to Firebase Storage
Adding Firebase to Project
First of all we have to connect our project to firebase and then add the required dependencies. For doing this just follow below steps.
Note: Below method of adding firebase will work only in android studio 2.2 and higher versions. If you are using any older version then follow this link to learn how to add firebase.
1. In android studio go to Tools > Firebase. It will open firebase assistant that allows us to add firebase to android studio within few clicks.
2. Now you will see a window as shown below. Just click on Storage section and then click Upload and download a file with Firebase Storage.
3. Click on Connect to Firebase, this will open a browser where you have to login to firebase using google account.
4. After that you will see a window as shown below. Here you can create a new firebase project or use an existing one. In my case I am using an existing project. Finally click on Connect to Firebase.
5. Now click on Add Firebase Storage to your app. In the next window click on Accept Changes to add all firebase storage related dependencies to android studio project.
Change Rules
By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.
Android Project
Now comes the actual coding part. In this simple example I have given two button, one to choose the image from gallery and another to upload it.
1. Firstly image is selected from gallery using file chooser and displayed in ImageView.
2. Before using firebase we have to get its instance and then using the instance create reference to firebase storage app. It can be done by following code.
//creating reference to firebase storage FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
3. Now a child reference is created and using it we call putFile() method to upload image to firebase storage.
4. If image is uploaded successfully then success message is shown otherwise error is shown in toast.
Below I have shared the full code for this.
Full Source Code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.firebaseimageupload.MainActivity" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Choose Image" android:id="@+id/chooseImg"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Upload Image" android:id="@+id/uploadImg"/> <ImageView android:layout_width="match_parent" android:layout_height="300dp" android:id="@+id/imgView"/> </LinearLayout>
MainActivity.java
package com.firebaseimageupload; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; 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 com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; public class MainActivity extends AppCompatActivity { Button chooseImg, uploadImg; ImageView imgView; int PICK_IMAGE_REQUEST = 111; Uri filePath; ProgressDialog pd; //creating reference to firebase storage FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chooseImg = (Button)findViewById(R.id.chooseImg); uploadImg = (Button)findViewById(R.id.uploadImg); imgView = (ImageView)findViewById(R.id.imgView); pd = new ProgressDialog(this); pd.setMessage("Uploading...."); chooseImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_PICK); startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST); } }); uploadImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(filePath != null) { pd.show(); StorageReference childRef = storageRef.child("image.jpg"); //uploading the image UploadTask uploadTask = childRef.putFile(filePath); uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { pd.dismiss(); Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); try { //getting image from gallery Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); //Setting image to ImageView imgView.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } } } }
Now run and test your app.
Screenshots
When you will login to firebase console the uploaded image will be shown something as given below.
Comment below if you have any queries related to above android upload image to firebase storage example.
The post Android Upload Image to Firebase Storage Tutorial appeared first on The Crazy Programmer.