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

Popular posts from this blog

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 the…

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 sync completed.
Update the project build config …

Flutter State Management With Provider and ChangeNotifier

Flutter state management with provider library and why it's so important? There are lots of topics in flutter which are very important but out of those state management of your flutter application is the most important and little bit complicated as well. So in this article, I will try to explain how to use the provider package for managing the state of flutter and dart application and how to access the data down the hierarchy of the widget tree without recreating the whole UI.



Basic knowledge of the state management and data flow in the Flutter



Before starting the coding I would like to explain some basics about the Flutter application so that you can understand, why it's important to manage the state of your application in the correct way.



In Flutter, everything is a widget and whenever the state of your application changes the UI is recreated the UI with the new data. Let's list out the topic or problem that we are going to explore about state management.



Challenge of St…