How to Make the Most of Firebase Storage (Tutorial)

Do you want to know how to use Google's Firebase Storage in Android? You've arrived to the right location.

Firebase Storage

Since you already know, storage is a must-have for any app, even if it's a static app with only 10 recipes for preparing delectable hot dogs.

You may be wondering why I need cloud storage for a static app. Allow me to explain.

If you're going to add photographs (rather than videos) to the recipe, you can do so straight in your app.

If you know how to utilize ASO (App Store Optimization) to improve an app's ranking on Google Play, you'll realize that most users despise apps that are too large.

Instead, you may utilize Firebase Cloud Storage to store the images/videos and then make them available to users on demand, reducing the size of your app.

This was a really simple example, but it demonstrated the importance of storage.

What is Firebase Cloud Storage, and how does it work?

Firebase Cloud Storage is a Google-owned cloud storage service for storing user-generated information such as images and movies. To lower the size of the app, users can download material on-demand.

The resume functionality of Firebase Cloud Storage allows users to upload a large file even if the connection breaks due to a variety of factors, thanks to the Firebase Cloud Storage SDK.

It's the same functionality as Google Drive or Dropbox. To preserve bandwidth, even if you disconnect and reconnect, your uploading resumes where it left off.

How Does Firebase Cloud Storage Work?

Working with Firebase Cloud Storage is a simple process.

You can upload any file and receive a URL to download it in return (of course there are some other ways to download the image but you got the idea).

But, for the purposes of this article, I'll bypass the login step and go directly to using Cloud Storage. This is due to the fact that I will not be releasing this software.

What Are the Rules for Using Firebase Cloud Storage?

Cloud Storage Rules are similar to Firebase Realtime Database Rules in that you set rules that allow or prevent specific users from accessing specific directories (called buckets in Firebase).

According to Firebase, you should only allow authenticated users to access Cloud Storage, hence the following are the requirements for that check:

service firebase.storage 
{
  match /b/{bucket}/o 
{
    match /{allPaths=**} 
    {
      allow read, write: if request.auth != null;
    }
  }
}

However, for the purposes of this lesson, I'm foregoing authentication and instead allowing anyone to access the storage. As a result, I'm going to change the regulations to:

service firebase.storage
{
  match /b/{bucket}/o 
{
    match /{allPaths=**} 
    {
      allow read, write:if true;
    }
  }
}

You can change the rules whatever you wish, such as allowing a specific person to view a specific file. The options are limitless.

Android Firebase Cloud Storage Integration

There are two steps involved in it:
  1. Connecting a Firebase project to an Android project.
  2. Firebase Cloud Storage is being added to an Android project.

Connecting Android Project to Firebase

Add firebase to your android project if you haven't antecedently.

Here's how to go about it:
  1. Create a new Android Studio project or open one that already exists.
  2. In Android Studio, open Firebase Assistant. Tools>Firebase is where you'll find it.
  3. It will open a right-hand window with all of the Firebase-related items. We'll extend the "Storage" dropdown because we're just interested in Firebase Cloud Storage. You'll notice a button that says "Upload and download a file with Cloud Storage," and you should click it.
  4. The first option you'll see is "Connect to Firebase," which you should select. If you are not currently logged in, it will prompt you to do so.
  5. After logging in, you'll be asked to create a new Firebase Project or select an existing one. Do whatever you want and then press the "Connect to Firebase" button.
That's all there is to it; your project is now connected to Firebase. Now it's time to integrate Firebase Storage into your project.

Adding Firebase Storage to your project

It's simple: simply click the "Add Cloud Storage to your app" button, accept the modifications, and you're done.

Start Uploading Files to Firebase Cloud Storage

Here is the code for creating the UI like this:

<?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">
 
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="500dp"
        android:layout_height="500dp"
        android:layout_margin="20dp"
        android:padding="25dp"
        android:background="@android:color/darker_gray"
         />
 
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageview"
        android:layout_alignRight="@+id/imageview"
        android:onClick="clearImage"
        android:src="@drawable/ic_cancel_black_24dp" />
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="50dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">
 
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="oneClicked"
            android:text="select image" />
 
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="uploadPhoto"
            android:text="Upload" />
 
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="downloadPhoto"
            android:text="Download" />
 
    </LinearLayout>
</RelativeLayout>

The grey rectangle is an image view that will show the image we are about to upload or download.

The image on the image view will be cleared by pressing the cross button in the upper right corner of the grey rectangle. Here's what happens when you press the button:

public void clearImage(View view) 
{
//We already have the reference of Image view, so now we are setting null to it
mImageView.setImageBitmap(null);
}

The "Select Image" button selects an image from the gallery and sets it to ImageView. The following is the code that will be run when the button is pressed:

//For the result method private, a request code is required to begin the activity final int PICK_IMAGE = 001;
//We're going to save the picture uri so we can use it to submit the file privately Uri imageUri;
 
//When the "Select Image" button is pressed, this function is invoked.
public void oneClicked(View view) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}

//When the user selects an image and returns to the app, this function will be called.
@Override
onActivityResult(int requestCode, int resultCode, @Nullable Intent data) is a protected void. 
{
//We must verify that the request code is the same and that the user selected an image.
if(requestCode ==PICK_IMAGE && resultCode == RESULT_OK)
{
    //Getting the Image URI
    imageUri = data.getData();
    try
   {
    //Changing the image's display mode to ImageView
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
    mImageView.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
super.onActivityResult(requestCode, resultCode, data);
}

The uploading of the selected photograph is now the most significant feature.

We'll need a reference to Firebase Cloud Storage, too, and we'll do it with this code:

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

This reference acts as a route for uploading files; if you push files to the reference we obtained with the above statement, the file will appear in the main directory.

We'll name the file "test image.png" and put it in the "images" folder.

As a result, we'll make a reference like this:

storageReference.child("images/test_image.png")

Now we'll call the putFile() method with the file URI we got when we picked the image as the argument. The file will be uploaded to that reference using this function.

We also need to keep track of progress, so we'll use the addOnCompleteListener call-back function ()

The following is the whole code for uploading the file, which will be called when the "Upload" button is pressed.

public void uploadPhoto(View view) 
{
    if(imageUri!=null)       storageReference.child("images/test_image.png").putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() 
{
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) 
{
            if(task.isSuccessful())
{
                Toast.makeText(MainActivity.this, "Upload completed", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(MainActivity.this, "Something went wrong: " + task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                Log.e(TAG, "onComplete: " +task.getException().getLocalizedMessage() );
            }
        }
    });
}

Post a Comment

Previous Post Next Post