Saving Data on Android


Saving data to the database



Download 19,28 Mb.
Pdf ko'rish
bet223/292
Sana24.01.2022
Hajmi19,28 Mb.
#407089
1   ...   219   220   221   222   223   224   225   226   ...   292
Bog'liq
Bailey J., Dominguez A., Djermanovic D. - Saving Data on Android (1st Edition) - 2019

Saving data to the database
Open the 
RealtimeDatabaseManager
 class. Add the 
database
 field to the class:
private
 val database = 
FirebaseDatabase
.getInstance()
FirebaseDatabase
 object is the main entry point to the database. The  
getInstance()
  method gets you the default 
FirebaseDatabase
 instance. There are 
overloads of 
getInstance()
 methods if you want to get the database for the specific 
URL or specific app.
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
215


Add 
POSTS_REFERENCE
 constant above the class declaration:
private
 const val 
POSTS_REFERENCE
 = 
"posts"
Next, add the function for creation of the 
Post
 object to the 
RealtimeDatabaseManager
 class:
private
 fun createPost(key: 
String
, content: 
String
): 
Post
 { 
    val user = authenticationManager.getCurrentUser() 
    val timestamp = getCurrentTime() 
    
return
 
Post
(key, content, user, timestamp) 
}
This function uses the 
AuthenticationManager
 class to get the current logged in 
user name, gets the current time and then returns newly created 
Post
 instance.
Next, add the function for saving the post to the database:
 
fun
 
addPost
(content: String, onSuccessAction: ()
 -> 
Unit

onFailureAction: () -> 
Unit
) { 
    
//1
 
    
val
 postsReference = database.getReference(POSTS_REFERENCE) 
    
//2
 
    
val
 key = postsReference.push().key ?: 
""
 
    
val
 post = createPost(key, content) 
 
    
//3
 
    postsReference.child(key) 
      .setValue(post) 
      .addOnSuccessListener { onSuccessAction() } 
      .addOnFailureListener { onFailureAction() } 
  }
Here's what happens here:
1.
DatabaseReference
 class represents a particular location in the database and it's 
used to refer to the location in the database to which you want to write to or read 
from. 
getReference()
 method returns a reference to the database root node. 
You won't save posts to the root node. Instead, you'll create a new node for the 
posts, which is why you added 
POSTS_REFERENCE
 constant earlier. You pass that 
constant to the 
getReference()
 and this returns a reference for the provided 
path. Now you can use 
postsReference
 to read or write data to this location.
2. Posts will be added as a child of the 
posts
 node. To add a post as a child it needs 
to have a unique key which will be used as a path to the specific post. The key 
needs to be unique because setting a value to the existing path would overwrite 
previous value on that path. You don't want that. You can use the 
push()
 method
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
216


to create an empty node with an auto-generated key. The 
push()
 method returns 
a database reference to the newly created node. You can call 
getKey()
 on the 
database reference to get the key to that reference. Next, you create a 
Post
 
instance that you'll save to the database and you store the key of that post so you 
can refer to it later.
3. To access the newly created location you can use the 
child()
 method that 
returns a reference to the location relative to the calling reference. Finally, you 
use the 
setValue(post)
 method to save the post to this location. The Realtime 
Database accepts multiple data types to store the data: 
String

Long

Double

Boolean

Map
, and 
List
. You can also use custom 
Kotlin or Java objects to store the data model class directly to the database as 
you're doing here. Finally, you attach 
OnSuccessListener
 that gets called if the 
post is saved to the database successfully, and 
OnFailureListener
 that gets 
called if the post saving failed.
Now open the 
AddPostActivity
 class and replace the 
TODO
 in the 
addPostIfNotEmpty()
 with the following:
val postMessage = postText.text.
toString
().trim() 
    
if
 (postMessage.isNotEmpty()) { 
      realtimeDatabaseManager.addPost(postMessage, 
        { showToast(getString(
R
.string.posted_successfully)) }, 
        { showToast(getString(
R
.string.posting_failed)) } ) 
      finish() 
    } 
else
 { 
      showToast(getString(
R
.string.empty_post_message)) 
    }
Here you get the text from 
EditText
 and if it's not empty you save the text to the 
database and you close the current activity.
Build and run your app. Click on the floating action button on the home screen, add 
some text and tap the 
Post
 button. Current activity gets closed and the home screen 
is shown. Posts should be displayed on the home screen. You'll add logic for that in a 
bit.
Open the database in the Firebase console and confirm that data is saved into the 
database. You should see your post here along with addiotional data that you added:
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
217


Good job! You'll add the logic for displaying posts on the home screen next.

Download 19,28 Mb.

Do'stlaringiz bilan baham:
1   ...   219   220   221   222   223   224   225   226   ...   292




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish