Javascript required
Skip to content Skip to sidebar Skip to footer

Upload Images Post to Firebase Android Studio

How to select image from mobile phone'south 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 costless space to upload Paradigm, PDF, DOC etc files with 1 GB/Day downloading limit. This is practiced for starter android apps. You tin can utilise Firebase Storage to upload and shop 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 telephone's storage to online Firebase Storage and store paradigm URL with epitome name into Firebase existent time database with unique ID, So they can exist access again via JSon format.

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

  1. Starting time a new android application project.
  2. Create, configure and connect Firebase project to your Android Studio Awarding.
  3. Add net permission.
  4. Add one TextView, one ImageView, 1 EditText and two Buttons in activity_main.xml layout file.
  5. Creating two String variables Storage_Path and Database_Path in MainActivity .
  6. Creating Push button, EditText, ImageView, Uri, StorageReference, DatabaseReference, ProgressDialog and int Image_Request_Code.
  7. AssignFirebaseStorage example to storageReference object.
  8. Assign FirebaseDatabase example with root database name.
  9. Assign ID's to all.
  10. Adding click listener to ChooseButton.
  11. Inside theChooseButton click listener Add Intent open Storage Image Picker code.
  12. AddonActivityResult() override method.
  13. CreatingGetFileExtension() method.
  14. CreatingUploadImageFileToFirebaseStorage() method.
  15. Adding click listener toUploadButton.
  16. Within theUploadButton, callUploadImageFileToFirebaseStorage() method.
  17. Creating new Java class named equallyImageUploadInfo .
  18. Final All source code.

one. Get-go a new android application project.

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

1. Openfirebase.google.com .

2. Click onGet Started button present on domicile screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add together Projection.

five. Enter your project name and select your land then click onCREATE PROJECT .

vi. Click onAdd together firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add awarding Parcel Proper 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-one certificate.

ix. At present hit the Register App button.

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

11. Adjacent footstep is to add togethergoogle-services.json inside your project. So open your projection and put( Copy )google-services.jsonfile inside YourProjectName/app binder. For case my firebase projection name isFirebase-AndroidJSon.com and so my app binder located isFirebase-AndroidJSon.com/app . At present re-create thegoogle-services.json file into app folderlike i did in below screenshot.

12. At present open your Project'southwardbuild.gradle(Project) file.

13. Add togetherclasspath 'com.google.gms:google-services:3.0.0' insidedependencies block.

14. Open up your projection'sbuild.gradle(Module:app) file.

15. Add together compile 'com.google.firebase:firebase-storage:10.0.ane' ,
compile 'com.google.firebase:firebase-auth:x.0.1' ,
compile 'com.firebase:firebase-client-android:two.four.0' and
compile 'com.google.firebase:firebase-database:10.0.1' insidedependencies block .

xvi. So addutilise plugin: 'com.google.gms.google-services' at the bottom of the page.

17. Now finally add belowpackagingOptions only bottom of buildTypes block like i did.

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

Final Screenshot :

eighteen. 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": truthful,  ".write": true  } }

20. Click onStorage -> 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.

three. Add together internet permission to your project :

Open your project's AndroidManifest.xml file and copy the beneath permission within information technology. Yous will discover the total AndroidManifest.xml file code at the bottom of this folio along with all source code.

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

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

TextView : TextView is used to show merely awarding championship on activity screen.

ImageView : ImageView is used to evidence selected image on activeness screen.

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

Buttons : Ane button for upload epitome, 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 Epitome"/>  <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 epitome to Firebase Storage"/>

5. Creating ii String variablesStorage_Path andDatabase_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, Uri,StorageReference, 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. AssignFirebaseStorage case to storageReferenceobject.

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

eight. 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 = (Push)findViewById(R.id.ButtonUploadImage);  // Assign ID'south 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. Calculation click listener to ChooseButton.

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

11. Inside theChooseButton click listener Add together Intent open Storage Epitome Picker code.

ChooseButton.setOnClickListener(new View.OnClickListener() {     @Override     public void onClick(View view) {          // Creating intent.         Intent intent = new Intent();          // Setting intent type equally epitome to select paradigm from phone storage.         intent.setType("image/*");         intent.setAction(Intent.ACTION_GET_CONTENT);         startActivityForResult(Intent.createChooser(intent, "Please Select Prototype"), Image_Request_Code);      } });

12. AddonActivityResult() override method :

UsingonActivityResult() method android developer can get whatever information dorsum 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() != nil) {          FilePathUri = data.getData();          try {              // Getting selected epitome into Bitmap.             Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);              // Setting upward bitmap selected image into ImageView.             SelectImage.setImageBitmap(bitmap);              // After selecting image modify choose button higher up text.             ChooseButton.setText("Image Selected");          }         grab (IOException e) {              e.printStackTrace();         }     } }

13. CreatingGetFileExtension() method.

// Creating Method to get the selected prototype 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. CreatingUploadImageFileToFirebaseStorage() method.

// Creating UploadImageFileToFirebaseStorage method to upload epitome on storage. public void UploadImageFileToFirebaseStorage() {      // Checking whether FilePathUri Is empty or not.     if (FilePathUri != nil) {          // Setting progressDialog Championship.         progressDialog.setTitle("Image is Uploading...");          // Showing progressDialog.         progressDialog.prove();          // Creating second StorageReference.         StorageReference storageReference2nd = storageReference.child(Storage_Path + Organization.currentTimeMillis() + "." + GetFileExtension(FilePathUri));          // Adding addOnSuccessListener to second StorageReference.         storageReference2nd.putFile(FilePathUri)                 .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {                     @Override                     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {                          // Getting prototype name from EditText and store into string variable.                         Cord TempImageName = ImageName.getText().toString().trim();                          // Hiding the progressDialog after done uploading.                         progressDialog.dismiss();                          // Showing toast bulletin after done uploading.                         Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();                          @SuppressWarnings("VisibleForTests")                         ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());                          // Getting epitome upload ID.                         String ImageUploadId = databaseReference.push().getKey();                          // Adding image upload id south 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 alter upload time.                 .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {                     @Override                     public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {                          // Setting progressDialog Title.                         progressDialog.setTitle("Paradigm is Uploading...");                      }                 });     }     else {          Toast.makeText(MainActivity.this, "Please Select Image or Add Paradigm Name", Toast.LENGTH_LONG).evidence();      } }

15. Adding click listener toUploadButton.

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

16. Inside theUploadButton, callUploadImageFileToFirebaseStorage() 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 asImageUploadInfo .

package com.androidjson.firebaseuploadimage_androidjsoncom;  /**  * Created past AndroidJSon.com on 6/10/2017.  */   public form ImageUploadInfo {      public Cord imageName;      public String imageURL;      public ImageUploadInfo() {      }      public ImageUploadInfo(String name, String url) {          this.imageName = proper name;         this.imageURL= url;     }      public String getImageName() {         render imageName;     }      public String getImageURL() {         return imageURL;     }  }

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

Lawmaking 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 course MainActivity extends AppCompatActivity {      // Binder path for Firebase Storage.     String Storage_Path = "All_Image_Uploads/";      // Root Database Proper noun 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 asking 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 example 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 = (Push button)findViewById(R.id.ButtonUploadImage);          // Assign ID's to EditText.         ImageName = (EditText)findViewById(R.id.ImageNameEditText);          // Assign ID'South to epitome view.         SelectImage = (ImageView)findViewById(R.id.ShowImageView);          // Assigning Id to ProgressDialog.         progressDialog = new ProgressDialog(MainActivity.this);          // Calculation 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 epitome from phone storage.                 intent.setType("image/*");                 intent.setAction(Intent.ACTION_GET_CONTENT);                 startActivityForResult(Intent.createChooser(intent, "Please Select Paradigm"), Image_Request_Code);              }         });           // Adding click listener to Upload epitome 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 && information != zippo && information.getData() != zero) {              FilePathUri = data.getData();              try {                  // Getting selected epitome into Bitmap.                 Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);                  // Setting up bitmap selected image into ImageView.                 SelectImage.setImageBitmap(bitmap);                  // Afterward selecting paradigm change choose button above text.                 ChooseButton.setText("Prototype Selected");              }             grab (IOException e) {                  eastward.printStackTrace();             }         }     }      // Creating Method to become 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 Championship.             progressDialog.setTitle("Image is Uploading...");              // Showing progressDialog.             progressDialog.show();              // Creating 2d StorageReference.             StorageReference storageReference2nd = storageReference.child(Storage_Path + Organisation.currentTimeMillis() + "." + GetFileExtension(FilePathUri));              // Adding addOnSuccessListener to 2nd StorageReference.             storageReference2nd.putFile(FilePathUri)                     .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {                         @Override                         public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {                              // Getting epitome proper noun from EditText and store into string variable.                             String TempImageName = ImageName.getText().toString().trim();                              // Hiding the progressDialog afterward 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 incorrect .                     .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 fourth dimension.                     .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {                         @Override                         public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {                              // Setting progressDialog Championship.                             progressDialog.setTitle("Image is Uploading...");                          }                     });         }         else {              Toast.makeText(MainActivity.this, "Delight Select Prototype or Add Image Name", Toast.LENGTH_LONG).bear witness();          }     }   }

Code for activity_main.xml layout file.

<?xml version="ane.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="assuming"         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 Hither"         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-eight"?> <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:characterization="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@mode/AppTheme">         <action android:name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.activity.Master" />                  <category android:proper noun="android.intent.category.LAUNCHER" />             </intent-filter>         </action>     </application>  </manifest>

Screenshots :

Firebase Storage

Download Code

bendrodtbodem1958.blogspot.com

Source: https://androidjson.com/upload-image-to-firebase-storage/