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
  3. Interesting article; I enjoyed the topic and your writing style about Telecom Consulting Services. and keep up the good work, please. I appreciate you sharing this content with us.

    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

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use. Create a flutter project So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter . Once your project is created you will get the default counter app and you try running the app in