Skip to main content

Quick Setup of Android Google Cloud Firebase Storage without background server

Google Cloud Firebase Storage is a good option if you are looking to store your files online without any background server and retrieve it later.
In this Tutorial, we are going to implement a very simple android demo app in which we will learn two things.

  1. How to upload the file to Google Cloud Firebase Storage.

  2. How to Download the file from Google Cloud Storage.


1.Project Setup for Firebase Storage


Create a Project with the name of Firebase Storage Demo in Android Studio.
Click on  Tool-Firebase.
Firebase Storage

Click on Storage.
Firebase Storage


  • Click on Upload and download a file with Firebase Storage.

  • Login to Firebase Console and add your app and follow the steps suggested.

  • Enter your project name same as it shows in your project.

  • Download the JSON file and store inside your app folder of the project.


Firebase Storage

Configure your project as given below and the below-given configuration as advice.
Project-level build.gradle (<project>/build.gradle):

buildscript {
dependencies {

// Add this line
classpath 'com.google.gms:google-services:3.0.0'
}
}

App-level build.gradle (<project>/<app-module>/build.gradle):

...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

includes Firebase Analytics by default help_outline

Finally, press "Sync now" in the bar that appears in the IDE.


Add the below dependency on your project build.gradle file and sync the project.
...
compile 'com.google.firebase:firebase-auth:9.8.0'
compile 'com.google.firebase:firebase-storage:9.8.0'

Now add required permission to AndroidMainfest.xml files.
...
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. Layout File Configuration for Firebase Storage


Now add the button to upload and download the file to your main layout files.
...
<TextView
android:layout_width="wrap_content"
android:textSize="16sp"
android:layout_height="wrap_content"
android:text="Hello Google Firebase Storage" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_upload"
android:text="Upload File"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_download"
android:text="Download File"/>

3.Method to Upload and Download the file from Firebase Storage


Create method to upload and download the file from Firebase Storage.
...
public void uploadFile(){
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = mStorageRef.child("images/myprofile.jpg");

riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}

public void downloadFile() {
File localFile = null;
try {
localFile = File.createTempFile("images", "jpg");
} catch (IOException e) {
e.printStackTrace();
}
StorageReference riversRef = mStorageRef.child("images/myprofile.jpg");
riversRef.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Successfully downloaded data to local file
// ...
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle failed download
// ...
}
});
}


Now add the on click listener to upload and download button to upload and download the file.
   mStorageRef = FirebaseStorage.getInstance().getReference();
Button btn_upload= (Button) findViewById(R.id.btn_upload);
Button btn_download= (Button) findViewById(R.id.btn_download);

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

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


4.Setting Firebase Rule


Now we are almost ready but we have done one more changes to Firebase google console so that our file is accessible publicly otherwise it will throw 403 error code. You need to implement some authentication method before publishing your app. Below is the different level of access rule in firebase console for file access.
// Anyone can read or write to the bucket, even non-users of your app.
// Because it is shared with Google App Engine, this will also make
// files uploaded via GAE public.
service firebase
.storage {
  match
/b/<your-firebase-storage-bucket>/o {
    match /
{allPaths=**} {
      allow read
, write;
   
}
 
}
}

// Access to files through Firebase Storage is completely disallowed.
// Files may still be accessible through Google App Engine or GCS APIs.
service firebase
.storage {
  match
/b/<your-firebase-storage-bucket>/o {
    match /
{allPaths=**} {
      allow read
, write: if false;
   
}
 
}
}

// Only authenticated users can read or write to the bucket
service firebase
.storage {
  match
/b/<your-firebase-storage-bucket>/o {
    match /
{allPaths=**} {
      allow read
, write: if request.auth != null;
   
}
 
}
}

// Grants a user access to a node matching their user ID
service firebase
.storage {
  match
/b/<your-firebase-storage-bucket>/o {
    /
/ Files look like: "user/<UID>/path/to/file.txt"
    match
/user/{userId}/{allPaths=**} {
      allow read
, write: if request.auth.uid == userId;
   
}
 
}
}

If have any query question in mind feel free to comment below.

Comments

  1. I generally check this kind of article and I found your article which is related to my interest. Genuinely it is good and instructive information, cloud solutions auckland Thankful to you for sharing an article like this.

    ReplyDelete
  2. Excellent post. I really enjoy reading and also appreciate your work. This concept is a good way to enhance knowledge. Keep sharing this kind of articles, Thank you.Wireless Network Design Houston

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit. What is Retrofit? If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps. Further, you can check the Retrofit Library here . So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website. Prerequisite for using the Retrofit for WordPress Android App Ther

How to Read and Write JSON data in Kotlin with GSON

Kotlin is now official language for Android development and it is well supported in Android Studio. So here in this tutorial, we are going to learn about how to read and write JSON data in Kotlin using GSON. If you would like to learn the java version of this tutorial check out the last tutorial " How to Read and Write JSON data using GSON ". Introduction In this tutorial, we will write two methods. In the first method, we will create a JSON file and in second method we will read the file and print in a text box.  If you like to know more about the basic entity of JSON you can check out Basic JSON entity here . What is JSON? JSON stands for J ava S cript O bject N otation JSON is a lightweight data-interchange format It is "self-describing" and easy to understand JSON is language independent and can we used in any language JSON Syntax Rules Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold