21.
Cloud Storage
Written by Harun Wangereka
With Realtime Database and Cloud Firestore, you saved data to the database. But what about files like photos, for example? While small pieces of data like posts, comments or users tend to be a few kilobytes of text, photos are much larger. Storing and retrieving photos extends the startup and loading time when reading the database. You don’t want to store photos in a database because it should be fast.
In this chapter, you’ll learn how to store media files using another Firebase feature — Cloud Storage. You’ll learn how to store an image in the cloud and how to get a URL to the image to display it in your app.
Note: If you skipped previous chapters, you need to set up Firebase to follow along. Do the following steps:
1.Create a project in the Firebase console.
2.Enable Google sign-in.
3.Set security rules to test mode to allow everyone read and write access.
4.Add google-service.json to both starter and final projects.
Note: To see how to do the steps above, go back to “Chapter 12: Firebase Overview” and “Chapter 13: Introduction to Firebase Realtime Database”.
Be sure to use the starter project from this chapter by opening the 21-cloud-storage folder and its starter project from the projects folder, rather than continuing with the final project you previously worked on. This chapter’s starter project has a few things added to it, including placeholders for the code to add in this chapter.
Cloud Storage Overview
Cloud Storage is a Firebase product used for saving files associated with your app. You can use it to store large documents or media files like images or videos.
Since Cloud Storage operates with large files, it’s fundamental to provide robust network connection mechanisms and fallbacks. Cloud Storage handles all the potential network problems for you. Depending on your connection, upload or download can take a while. If you lose the network connection in the middle of an upload or a download, the transfer will continue where it left off, after you reconnect to the network. This makes transferring your data very efficient.
Cloud Storage also has security features that will safely store your files away from the public. You can decide who can write data to and read data from the storage.
The foundations of Cloud Storage are the folders that you create to organize your data. You can then decide which users can access which folders.
There’s more theory you could learn, but for now, you’ll use the Firebase console to set up Cloud Storage. You’ll use the WhatsUp app to store, download and display images to users on the app screen.
Getting started
Open your WhatsUp app in the Firebase console. Select Storage from the Build menu on the left.
Tap Get started to set up Cloud Storage.
For your first step, you need to set up security rules for your storage. Leave the default rules that allow reads and writes from authenticated users. Tap Next.
In the second step, you need to choose the location for your Cloud Storage. You can choose the location of your preference from the drop-down list that appears. Tap Done once you finish. Your Cloud Storage is now ready for use.
You can see that your storage is empty; you haven’t added any files yet. Next, you’re going to change this. Tap the little folder icon in the top-right corner to create a new folder.
Name your folder photos and tap Add folder. You’ll use this folder to store the photos.
Cloud Storage is now set up and ready for use. Next, you’ll integrate it with your app.
Integrating Cloud Storage
Open the starter project for this chapter. Build and run. You’ll see the main screen for adding posts.
On this empty screen find a floating action button in the bottom-right corner. Very soon you’ll implement action for that button. Then, once you tap it, it will open File Explorer on your device.
This is where you’ll choose the image that you want to store to Cloud Storage.
Note: File Explorers may vary in appearance depending on your Android version, phone manufacturer and whether you’ve installed third-party file manager applications.
Next, you’ll implement the logic for uploading the image. When a user selects an image, you’ll upload it to Cloud Storage. Then, you’ll get a URL of that image which you’ll use to display the image on the home screen.
Open CloudStorageManager.kt , replace the TODO inside uploadPhoto() with:
//1
val photosReference = firebaseStorage.getReference(PHOTOS_REFERENCE)
//2
selectedImageUri.lastPathSegment?.let { segment ->
//3
val photoReference = photosReference.child(segment)
//4
photoReference.putFile(selectedImageUri)
//5
.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
val exception = task.exception
if (!task.isSuccessful && exception != null) {
throw exception
}
return@Continuation photoReference.downloadUrl
})
//6
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
onSuccessAction(downloadUri.toString())
}
}
}
In the code above:
- First, you get a reference to the photos folder that you created earlier, by calling
getReference()onfirebaseStorage. This is where you’ll upload your photo. - You get
lastPathSegmentof the image URI. You’ll use it as the name of the file that you’re going to save. - Get a reference that points to the location to which you’ll store the image.
- Here you call
putFile()to store the image tophotosReference. You also pass in the content URI of the image. This method stores the image asynchronously. It returns an instance ofUploadTaskthat you’ll use to track the upload progress. - Next, you call
continueWithTask()on theUploadTaskobject to get the download URL of the image you’re uploading when the image upload finishes. When importing, usecom.google.android.gms.tasks.Continuation. - If the
Taskrequest is successful, you returnphotoReference.downloadUrl. Otherwise, you throw an exception. - Finally, you attach
OnCompleteListenerso you’ll receive a notification when the upload finishes. - If the task is successful, you get the download URI by calling
task.result. You pass that result toonSuccessAction().
Now, open HomeActivity.kt, below your onPhotoUploadSuccess() add:
private val pickImages = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
uri?.let { selectedImageUri ->
binding.progressbar.visibility = View.VISIBLE
cloudStorageManager.uploadPhoto(selectedImageUri, ::onPhotoUploadSuccess)
}
}
Here, you using the new Activity Result API to register your pickImages callback. This callback uses an inbuilt contract, ActivityResultContracts.GetContent(), in the API. It makes it easy for you to launch the image picker option. When you select your image from the File Explorer, you’ll get the URI of the selected image from the callback. You pass the URI using uploadPhoto() on the cloudStorageManager object.
Finally, in initialize() , replace the TODO inside addPostFab click-listener with:
pickImages.launch(IMAGE_TYPE)
With this line, you launch your pickImages contract. You pass mimeType for your content. In this case, it’s image/jpeg since you only want to upload image files. With this, your app is ready to choose and upload images to Cloud Storage. :]
Build and run. Now, open the File Explorer by using the floating button. Select an image from the File Explorer. It will immediately upload to Cloud Storage.
When the upload finishes, you’ll see the image on the home screen.
Go to the Firebase console and open your app’s Cloud Storage. You’ll see the photo you uploaded in the photos folder.
Awesome! You’ve successfully connected your app to Firebase Cloud Storage!
Key points
- Cloud Storage is a Firebase product used for saving files associated with your app.
- If you lose a network connection in the middle of the upload or a download, the transfer will continue where it left off after you reconnect to the network.
- Cloud Storage also has security features that will make your files secure.
- The foundations of Cloud Storage are folders that you can create to organize your data.
Where to go from here?
This chapter was only an introduction to Cloud Storage to show you how to store media files to the cloud. You learned how to set up Cloud Storage and how to upload and download files from it. Cloud Storage has many other features. To learn more about them visit the official guidelines https://firebase.google.com/docs/storage/android/start.