Saving Data on Android


Querying and filtering data



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

Querying and filtering data
To show how to query data you'll add another feature to the app. You'll enable users 
to add comments to the post.
Open 
RealtimeDatabaseManager
 class and add two more constants above class 
declaration:
private
 const val 
COMMENTS_REFERENCE
 = 
"comments"
 
private
 const val 
COMMENT_POST_ID_PATH
 = 
"postId"
COMMENTS_REFERENCE
 is used to refer to the location of comments and 
COMMENT_POST_ID_PATH
 is used when building a query. You'll do that in a bit.
Next, add 
commentsValues
 and 
commentsValueEventListener
 fields to the 
RealtimeDatabaseManager
 class:
private
 val commentsValues = 
MutableLiveData
<
List
<
Comment
>>() 
private
 lateinit 
var
 commentsValueEventListener: 
ValueEventListener
Add the  
createComment
 function which is just a helper function for building a  
Comment
 instance:
private
 fun createComment(postId: 
String
, content: 
String
): 
Comment
 { 
    val user = authenticationManager.getCurrentUser() 
    val timestamp = getCurrentTime() 
    
return
 
Comment
(postId, user, timestamp, content) 
}
Now add the 
addComment
 function:
fun addComment(postId: 
String
, content: 
String
) { 
    val commentsReference = 
database.getReference(
COMMENTS_REFERENCE

    val key = commentsReference.push().key ?: 
""
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
224


    val comment = createComment(postId, content) 
 
    commentsReference.child(key).setValue(comment) 
}
This function saves the comment to the database. It uses the same logic as the post 
saving function so you should be familiar with this by now.
Now open the  
PostDetailsActivity
 class, navigate to the 
initializeClickListener
 function and replace the  
TODO
 inside the  
addCommentButton
 click listener with the following:
val comment = commentEditText.text.
toString
().trim() 
  
if
 (comment.isNotEmpty()) { 
    realtimeDatabaseManager.addComment(post.id, comment) 
    commentEditText.text.clear() 
  } 
else
 { 
    showToast(getString(
R
.string.empty_comment_message)) 
}
Here you get the text from the edit text and if it is not empty you save the comment 
to the database.
Build and run your app. Tap on any post from the list, add a comment in the edit text 
and click 
Add comment
 button.
Edit text gets cleared but nothing happens on the UI. Go to the Firebase console. You 
will see there that comment is saved to the database.
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
225


You can see there that comment has a 
postId
 child. This is how you'll know to which 
post comment belongs.
Now you can add logic for reading the comments from the database.
Open 
RealtimeDatabaseManager
 class again and add the  
listenForPostCommentsValueChanges
 function:
private
 fun listenForPostCommentsValueChanges(postId: 
String
) { 
    commentsValueEventListener = object : 
ValueEventListener
 { 
      
override
 fun onCancelled(databaseError: 
DatabaseError
) { 
        
/* No op */
 
      } 
 
      
override
 fun onDataChange(dataSnapshot: 
DataSnapshot
) { 
        
if
 (dataSnapshot.exists()) { 
          val comments = dataSnapshot.children.mapNotNull 
{ it.getValue(
Comment
::
class
.
java
) }.
toList
() 
          
commentsValues
.
postValue
(
comments

        } 
else
 { 
          commentsValues.postValue(emptyList()) 
        } 
      } 
    } 
 
    database.getReference(
COMMENTS_REFERENCE

          
//1
 
        .orderByChild(
COMMENT_POST_ID_PATH

        
//2
 
        .equalTo(postId) 
        .addValueEventListener(commentsValueEventListener) 
}
This function listens for comments value updates and it is very similar to the 
listenForPostsValueChanges
, but there are two differences:
1. The 
orderByChild
 method returns a 
Query
 instance where children are ordered 
by the 
postId
 value. A query is a request for data or information from a database.

Download 19,28 Mb.

Do'stlaringiz bilan baham:
1   ...   222   223   224   225   226   227   228   229   ...   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