Uploading image in Firebase cloud in Android Application

In this tutorial we are going to implement firebase in android app and we will upload a image using Google FireBase. To know more about Firebase click here.

Step 1: Connecting Firebase to your application

Create a simple android studio project and then after creating click on Tools in menubar in android application and select option Firebase

After this you will see a Assistant panel opened in the right side of the android studio. Now in Firebase Assistant click on the storage.Now in storage click on Upload and download a file with cloud storage.

Now after this click on Connect to Firebase option in Firebase assistant. And after this a window will occur shown below. Click on Connect To Firebase button.

after this step A tab will open in Your default browser for your google sign in if you have already signed in your browser Tab will not occur.

Now after this in Firebase Assistant click on the button Add cloud storage to your app. After this a window will occur which ask you to add required dependencies.

Click on Accept Changes. Now it will add required dependencies and will re-sync the project. Now we have successfully connected to the firebase .

Step 2: Layout

We are going to create and imageView and two buttons for selecting image and uploading it to fire base.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context="com.example.kaushal.cardsview.MainActivity">
    <ImageView
        android:id="@+id/image_"
        android:layout_width="match_parent"
        android:layout_height="380dp"
        />
        <Button
            android:id="@+id/select_"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Select"
            android:onClick="selectImage"
            android:gravity="center"
            />

    <Button
        android:id="@+id/upload_"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Upload"
        android:onClick="uploadImage"
        android:gravity="center"
        />

</LinearLayout>

 

Step 2: MainActivity.java

package com.example.kaushal.cardsview;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
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.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.net.MalformedURLException;

public class MainActivity extends AppCompatActivity {
    private StorageReference mStorage;
    public Uri uri;
    ImageView img;
    ProgressDialog pd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img=findViewById(R.id.image_);
        pd=new ProgressDialog(this);
        pd.setMessage("Uploading...");
        mStorage= FirebaseStorage.getInstance().getReference();


    }
    void selectImage(View view){
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,123);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==123 && resultCode==RESULT_OK && data!=null){
            uri=data.getData();
            img.setImageURI(uri);

        }
    }
    void uploadImage(View view){
        pd.show();
        StorageReference riversRef=mStorage.child("image1.jpg");
        riversRef.putFile(uri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // Get a URL to the uploaded content
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                       Toast.makeText(MainActivity.this,"Successfull",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                       
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle unsuccessful uploads
                        // ...
                    }
                });
    }
}

Now in above code we have two tasks to accomplish 1.selecting a image form phone 2.uploading to firebase.

Please click here to understand how we are selecting image form Phone.

Now to upload a image we have used a void uploadImage() method in which we have used the firebase method provided in the Firebase assistant.

 

Step 3: Add Internet permission

In Androidmainfest.xml add the internet permission.

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

Now run the app and upload a file.

Now check the Storage section in Firebase console.

So this is a basic example how we upload a file using Google Firebase. If you have any query related to website kindly ask in comment Section.

 

About kaushal97

Android Enthusiast

Leave a Reply

Your email address will not be published. Required fields are marked *