Home Android & Kotlin Books Saving Data on Android

20
Cloud Storage Written by Dean Djermanović

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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 just a few kilobytes of text, photos are much larger. You don’t want to store photos in a database because it should be fast; storing and retrieving photos would extend both the startup time and loading time when reading the database.

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 to 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 setup 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 the 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 11: Firebase Overview” and “Chapter 12: Introduction to Firebase Realtime Database”.

Be sure to use the starter project from this chapter by opening the 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 another 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 of 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 and you’ll use the WhatsUp app to store images and to download and display them to users on the app screen.

Getting started

Open your WhatsUp app in the Firebase console. Select Storage from the Develop menu on the left. You’ll see the following screen:

Integrating Cloud Storage with your app

Open the starter project for this chapter then build and run the app. You’ll see an empty screen with a floating action button in the bottom-right corner. When you click on the button, a File Explorer on your device will open:

fun uploadPhoto(selectedImageUri: Uri, onSuccessAction: (String) -> Unit) {
  // 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
			// 6
          if (!task.isSuccessful && exception != null) {
            throw exception
          }
          return@Continuation photoReference.downloadUrl
        })
        // 7
        .addOnCompleteListener { task ->
        	// 8
          if (task.isSuccessful) {
            val downloadUri = task.result
            onSuccessAction(downloadUri.toString())
          }
        }
  }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  super.onActivityResult(requestCode, resultCode, data)
  if (requestCode == CHOOSE_IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
    val selectedImageUri = data?.data ?: return
    cloudStorageManager.uploadPhoto(selectedImageUri, ::onPhotoUploadSuccess)
  }
}

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 the Cloud Storage are folders that you can create to organize your data.

Where to go from here?

This chapter was just 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.