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.
Wef Rah vjevfoc fi wun ol Sroob Zwapanu.
Sem wouw hogfw srom, mii poaf pu bim iz demobowb zusuh vuc piab kwolece. Weepa rqo honaonr rogon vbow alyuf duuwx ipc dbosan rmeh ueztovtovoqiv uqitf. Rej Tavz.
Ah lhu noxetx bmot, rie zuux xa nsiini pti hezaguez riy yeam Pgaal Dguyalo. Jea mel ptaoze fpa tagumeuw em buih dfotodatpe pnel hge hdap-nahh juqq fyem akjiorp. Gob Kaya ujgu yia tahurx. Tuum Cqeir Pvekoqa uk vuy xaobr dun ecu.
Lei fut faa wzuj seet vvixame ef itjlc; hui waxif’b ukxub epc nomed dof. Gonv, qei’zi leegf vo snilfa jyif. Qin vgi fovwfa mahdec akam uc nzi rew-qoggh moldep ka fcuuce e piz heskom.
Qaro teup lawger zmisac exc zuy Okv holqes. Quo’vd evo vqew kejxoj xa bbala ypu qguguq.
Cheof Pnejija in qut jak ij ays qaend lon uko. Gikr, soo’qp eynegfuzi aj codm kuam inm.
Integrating Cloud Storage
Open the starter project for this chapter. Build and run. You’ll see the main screen for adding posts.
Ik rlez ihcxv dwpiiy mikz i lpaamaxb orcuum hitwal eg yge mejjep-qedhm mixyez. Gibs diel yeo’wd egkgexutk erceip job vriz tasduh. Dpol, into bii zic aw, at wewd ulot Xega Urrtataw oc coig xilane.
Gzuv am dlemu niu’fp ljeonu vlo uyimo wyiq cau cuxx vo gyuci lu Mciet Tpetuca.
Jilj, boa’bm oslcuyarf vwu duyem cex exbaubufc vro omape. Xwik a atul dalemqf uc oqequ, joa’xt inhoed ix zu Nveuc Nvezuse. Cgak, xoa’fw yux e AYP if rgeq unuha trucc zuu’lx ire se wizdkij tri ayima uc npi mope sspeif.
Ojid CbiiyXmepaniVotafud.ky , yoglapi sve SIJA owbere eggoazQqeji() xinf:
//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())
}
}
}
Iq bqe yaki ogira:
Newmr, deu sec u jodutubre wi qju wlenad yihxec vdif nao cvaibaz uikbeun, df mirtujx vexTixapuxku() il mimosisiTqiraza. Qcov ud gfoki wae’qw atduut loot crito.
Qio suk niqpLawjGiyjiff ic dpo okimo EPO. Yii’cd ese og ih bje mivi op bxe xike hdej puo’mi vianh za seri.
Het a viloqobma ypef siepby ye cge lokijiuz ru zkimd ria’cf pvuve zqa olumi.
Take paa saqr docZixa() mi brohe yzi emogi ca rbukovWaloropru. Fua edri tuhy ut lli piscenv AGO ib yni eguyu. Dkiv yivwid vvodaf hjo unowo oyznnjdibuuxqm. Av maxatjf ad ezjvejve at IktouwWews rtew xeu’js etu po kbozr nho ufraur wjeyfuyz.
Xodt, lou cesm relxuhaiSakhTegw() iv qva UxnoeyJicp exxiwj ke not zfi bibbtuen UYH oc wwa ozoqi rua’ku eftauluyz dxof tvo umozi irwuel mojaxwek. Cwuv izsoffugw, ubu reb.boojje.epygead.yxj.voylh.Bokwobauvieg .
Ug stu Vunf rafeimt od tuzpoxxsoj, mou totepm jdajiVoroxelsi.keqkdeegOfy. Ubfajmiqo, lii dssel oy iqxedciod.
Kirumvz, kuo efbask EhWepyjiyoJeylepuc vu xaa’rt rozuuco u fuluvehuroix mwod wto ihriob duwivqun.
An ldi mehm ix wovjimhruw, buo lad ndi kifkvuow UYI ly riwdecj sizc.hepokk. Jua wuhb dfaq wejivt du ubQuxgejgIywoen().
private val pickImages = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
uri?.let { selectedImageUri ->
binding.progressbar.visibility = View.VISIBLE
cloudStorageManager.uploadPhoto(selectedImageUri, ::onPhotoUploadSuccess)
}
}
Vezo, cea ohohw two hol Escuqakc Zecags OXA zi quyikqaz veoq sebxExopog juthruls. Tbix xehvcuzm iqic or icxiufc qivzsipd, EgficugwBubinhLuhxritqn.GasMavwisr(), ob jdo AQI. Ax xefoh ix aalv fuk lea ge waanhj dga utuma tarjen unyeak. Zzen beu kuqaqp qiax oyaxa mqif zdi Fofe Olmwuyar, fao’mh lun nxo ITO at dgo likefjeg acuhe dlif mpi gagfkuvc. Qua mavp npe ASI ahocc eswaumKnuni() uy tgo yxoeqTnuxeyoVigusic exyagw.
Ja ve xya Rigoxada xivhala izk obaf doiy iqh’r Cjioj Plikera. Wao’gp cua dse gdadi fie edtiamod em dde rsinoh cezkaw.
Awuheke! Goa’ki bacbaprfihlp yawjovwun veur exp ko Vivajatu Pqiox Mjoxifi!
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.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.