Android Upload Image with Text to Firebase Storage Tutorial

How to select image from mobile phone’s storage or gallery and upload to online Firebase storage along with Image Name text and store image name into Firebase real time database.

Firebase gives us 5 GB of free space to upload Image, PDF, DOC etc files with 1 GB/Day downloading limit. This is good for starter android apps. You can use Firebase Storage to upload and store your app’s images and also to upload your personal files.

So in this tutorial we would going Create an android application which would upload the selected image from phone’s storage to online Firebase Storage and store image URL with image name into Firebase real time database with unique ID, So they can be access again via JSon format.

Contents in this project Upload Image with Text to Firebase Storage :

  1. Start a new android application project.
  2. Create, configure and connect Firebase project to your Android Studio Application.
  3. Add internet permission.
  4. Add one TextView, one ImageView, One EditText and two Buttons in activity_main.xml layout file.
  5. Creating two String variables Storage_Path and Database_Path in MainActivity .
  6. Creating Button, EditText, ImageView, Uri, StorageReference, DatabaseReference, ProgressDialog and int Image_Request_Code.
  7. Assign FirebaseStorage instance to storageReference object.
  8. Assign FirebaseDatabase instance with root database name.
  9. Assign ID’s to all.
  10. Adding click listener to ChooseButton.
  11. Inside the ChooseButton click listener Add Intent open Storage Image Picker code.
  12. Add onActivityResult() override method.
  13. Creating GetFileExtension() method.
  14. Creating UploadImageFileToFirebaseStorage() method.
  15. Adding click listener to UploadButton.
  16. Inside the UploadButton, call UploadImageFileToFirebaseStorage() method.
  17. Creating new Java class named as ImageUploadInfo .
  18. Final All source code.

1. Start a new android application project.

2. Create, configure and connect Firebase project to your Android Studio Application :-

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.google.firebase:firebase-storage:10.0.1’ , 
compile ‘com.google.firebase:firebase-auth:10.0.1’ , 
compile ‘com.firebase:firebase-client-android:2.4.0’ and
compile ‘com.google.firebase:firebase-database:10.0.1’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

18. Open firebase.google.com , Select your project. Now click on Database -> Rules .

19. Add below rules in it just like i did in above screenshot.

{
 "rules": {
 ".read": true,
 ".write": true
 }
}

20. Click on Storage -> Rules.

21. Add Storage rules like i did. You need to replace my appspot url with yours.

service firebase.storage {
 match /b/fir-imageupload-e9031.appspot.com/o {
 match /{allPaths=**} {
 allow read, write: if true;
 }
 }
}

22. You can find your Appspot url on Storage -> Files.

3. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

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

4. Add one TextView, one ImageView, One EditText and two Buttons in activity_main.xml layout file :

TextView : TextView is used to show just application title on activity screen.

ImageView : ImageView is used to show selected image on activity screen.

EditText :  EditText is used to get name of image from user.

Buttons : One button for upload image, one for select image.

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Firebase Image Upload Tutorial"
    android:id="@+id/textview"
    android:textStyle="bold"
    android:textSize="20dp"
    android:gravity="center"
    android:layout_marginTop="20dp"/>

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:id="@+id/ShowImageView"
    android:layout_below="@+id/textview"
    android:layout_marginTop="20dp"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ButtonChooseImage"
    android:layout_below="@+id/ShowImageView"
    android:layout_marginTop="20dp"
    android:text="Choose Image"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ImageNameEditText"
    android:layout_below="@+id/ButtonChooseImage"
    android:layout_marginTop="20dp"
    android:hint="Enter Image Name Here"
    android:gravity="center"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ButtonUploadImage"
    android:layout_below="@+id/ImageNameEditText"
    android:layout_marginTop="20dp"
    android:text="Upload image to Firebase Storage"/>

5. Creating two String variables Storage_Path and Database_Path in MainActivity .

Storage_Path : Automatically create folder in Firebase Storage to store images.

Database_Path : Create a root database on firebase real time database to store image URL with image name text.

// Folder path for Firebase Storage.
String Storage_Path = "All_Image_Uploads/";

// Root Database Name for Firebase Database.
String Database_Path = "All_Image_Uploads_Database";

6. Creating Button, EditText, ImageView, UriStorageReference, DatabaseReference, ProgressDialog and int Image_Request_Code.

// Creating button.
Button ChooseButton, UploadButton;

// Creating EditText.
EditText ImageName ;

// Creating ImageView.
ImageView SelectImage;

// Creating URI.
Uri FilePathUri;

// Creating StorageReference and DatabaseReference object.
StorageReference storageReference;
DatabaseReference databaseReference;

// Image request code for onActivityResult() .
int Image_Request_Code = 7;

ProgressDialog progressDialog ;

7. Assign FirebaseStorage instance to storageReference object.

storageReference = FirebaseStorage.getInstance().getReference();

8. Assign FirebaseDatabase instance with Root database name.

databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

9. Assign ID’s to all.

//Assign ID'S to button.
ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
UploadButton = (Button)findViewById(R.id.ButtonUploadImage);

// Assign ID's to EditText.
ImageName = (EditText)findViewById(R.id.ImageNameEditText);

// Assign ID'S to image view.
SelectImage = (ImageView)findViewById(R.id.ShowImageView);

// Assigning Id to ProgressDialog.
progressDialog = new ProgressDialog(MainActivity.this);

10. Adding click listener to ChooseButton.

ChooseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

      
    }
});

11. Inside the ChooseButton click listener Add Intent open Storage Image Picker code.

ChooseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Creating intent.
        Intent intent = new Intent();

        // Setting intent type as image to select image from phone storage.
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);

    }
});

12. Add onActivityResult() override method :

Using onActivityResult() method android developer can get any data back from opened application. So we get the selected image using this method and set selected image into ImageView. After that we would store the image path into URI.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null) {

        FilePathUri = data.getData();

        try {

            // Getting selected image into Bitmap.
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

            // Setting up bitmap selected image into ImageView.
            SelectImage.setImageBitmap(bitmap);

            // After selecting image change choose button above text.
            ChooseButton.setText("Image Selected");

        }
        catch (IOException e) {

            e.printStackTrace();
        }
    }
}

13. Creating GetFileExtension() method.

// Creating Method to get the selected image file Extension from File Path URI.
public String GetFileExtension(Uri uri) {

    ContentResolver contentResolver = getContentResolver();

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

    // Returning the file Extension.
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

}

14. Creating UploadImageFileToFirebaseStorage() method.

// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {

    // Checking whether FilePathUri Is empty or not.
    if (FilePathUri != null) {

        // Setting progressDialog Title.
        progressDialog.setTitle("Image is Uploading...");

        // Showing progressDialog.
        progressDialog.show();

        // Creating second StorageReference.
        StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

        // Adding addOnSuccessListener to second StorageReference.
        storageReference2nd.putFile(FilePathUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        // Getting image name from EditText and store into string variable.
                        String TempImageName = ImageName.getText().toString().trim();

                        // Hiding the progressDialog after done uploading.
                        progressDialog.dismiss();

                        // Showing toast message after done uploading.
                        Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                        @SuppressWarnings("VisibleForTests")
                        ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());

                        // Getting image upload ID.
                        String ImageUploadId = databaseReference.push().getKey();

                        // Adding image upload id s child element into databaseReference.
                        databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                    }
                })
                // If something goes wrong .
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {

                        // Hiding the progressDialog.
                        progressDialog.dismiss();

                        // Showing exception erro message.
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                })

                // On progress change upload time.
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                        // Setting progressDialog Title.
                        progressDialog.setTitle("Image is Uploading...");

                    }
                });
    }
    else {

        Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

    }
}

15. Adding click listener to UploadButton.

UploadButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

    }
});

16. Inside the UploadButton, call UploadImageFileToFirebaseStorage() method.

UploadButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

            // Calling method to upload selected image on Firebase storage.
            UploadImageFileToFirebaseStorage();

    }
});

17. Creating new Java class named as ImageUploadInfo .

package com.androidjson.firebaseuploadimage_androidjsoncom;

/**
 * Created by AndroidJSon.com on 6/10/2017.
 */


public class ImageUploadInfo {

    public String imageName;

    public String imageURL;

    public ImageUploadInfo() {

    }

    public ImageUploadInfo(String name, String url) {

        this.imageName = name;
        this.imageURL= url;
    }

    public String getImageName() {
        return imageName;
    }

    public String getImageURL() {
        return imageURL;
    }

}

18. Final All source code for Upload Image with Text to Firebase Storage Tutorial :

Code for MainActivity.java file.

package com.androidjson.firebaseuploadimage_androidjsoncom;
import android.app.ProgressDialog;
import android.content.ContentResolver;
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.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
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.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    // Folder path for Firebase Storage.
    String Storage_Path = "All_Image_Uploads/";

    // Root Database Name for Firebase Database.
    String Database_Path = "All_Image_Uploads_Database";

    // Creating button.
    Button ChooseButton, UploadButton;

    // Creating EditText.
    EditText ImageName ;

    // Creating ImageView.
    ImageView SelectImage;

    // Creating URI.
    Uri FilePathUri;

    // Creating StorageReference and DatabaseReference object.
    StorageReference storageReference;
    DatabaseReference databaseReference;

    // Image request code for onActivityResult() .
    int Image_Request_Code = 7;

    ProgressDialog progressDialog ;

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

        // Assign FirebaseStorage instance to storageReference.
        storageReference = FirebaseStorage.getInstance().getReference();

        // Assign FirebaseDatabase instance with root database name.
        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

        //Assign ID'S to button.
        ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
        UploadButton = (Button)findViewById(R.id.ButtonUploadImage);

        // Assign ID's to EditText.
        ImageName = (EditText)findViewById(R.id.ImageNameEditText);

        // Assign ID'S to image view.
        SelectImage = (ImageView)findViewById(R.id.ShowImageView);

        // Assigning Id to ProgressDialog.
        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to Choose image button.
        ChooseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Creating intent.
                Intent intent = new Intent();

                // Setting intent type as image to select image from phone storage.
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);

            }
        });


        // Adding click listener to Upload image button.
        UploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    // Calling method to upload selected image on Firebase storage.
                    UploadImageFileToFirebaseStorage();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null) {

            FilePathUri = data.getData();

            try {

                // Getting selected image into Bitmap.
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

                // Setting up bitmap selected image into ImageView.
                SelectImage.setImageBitmap(bitmap);

                // After selecting image change choose button above text.
                ChooseButton.setText("Image Selected");

            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    // Creating Method to get the selected image file Extension from File Path URI.
    public String GetFileExtension(Uri uri) {

        ContentResolver contentResolver = getContentResolver();

        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

        // Returning the file Extension.
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

    }

    // Creating UploadImageFileToFirebaseStorage method to upload image on storage.
    public void UploadImageFileToFirebaseStorage() {

        // Checking whether FilePathUri Is empty or not.
        if (FilePathUri != null) {

            // Setting progressDialog Title.
            progressDialog.setTitle("Image is Uploading...");

            // Showing progressDialog.
            progressDialog.show();

            // Creating second StorageReference.
            StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

            // Adding addOnSuccessListener to second StorageReference.
            storageReference2nd.putFile(FilePathUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            // Getting image name from EditText and store into string variable.
                            String TempImageName = ImageName.getText().toString().trim();

                            // Hiding the progressDialog after done uploading.
                            progressDialog.dismiss();

                            // Showing toast message after done uploading.
                            Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                            @SuppressWarnings("VisibleForTests")
                            ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());

                            // Getting image upload ID.
                            String ImageUploadId = databaseReference.push().getKey();

                            // Adding image upload id s child element into databaseReference.
                            databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                        }
                    })
                    // If something goes wrong .
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {

                            // Hiding the progressDialog.
                            progressDialog.dismiss();

                            // Showing exception erro message.
                            Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })

                    // On progress change upload time.
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                            // Setting progressDialog Title.
                            progressDialog.setTitle("Image is Uploading...");

                        }
                    });
        }
        else {

            Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

        }
    }


}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.androidjson.firebaseuploadimage_androidjsoncom.MainActivity"
    android:layout_margin="20dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Firebase Image Upload Tutorial"
        android:id="@+id/textview"
        android:textStyle="bold"
        android:textSize="20dp"
        android:gravity="center"
        android:layout_marginTop="20dp"/>

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:id="@+id/ShowImageView"
        android:layout_below="@+id/textview"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonChooseImage"
        android:layout_below="@+id/ShowImageView"
        android:layout_marginTop="20dp"
        android:text="Choose Image"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ImageNameEditText"
        android:layout_below="@+id/ButtonChooseImage"
        android:layout_marginTop="20dp"
        android:hint="Enter Image Name Here"
        android:gravity="center"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonUploadImage"
        android:layout_below="@+id/ImageNameEditText"
        android:layout_marginTop="20dp"
        android:text="Upload image to Firebase Storage"/>

</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebaseuploadimage_androidjsoncom">

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots :

Firebase Storage

Download Code

Leave a Reply

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