Saving Data on Android


Fetching data from the database



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

Fetching data from the database
When it comes to reading the data from the database you have two options. You can 
read the data once or you can be notified whenever data changes. Since you want to 
see every new post from other users instantly you'll implement the second option.
To get all posts from the database and listen for value changes you need to use 
ValueEventListener
. You need to attach this listener to the specific location in the 
database that you want to listen for changes from.
Open 
RealtimeDatabaseManager
 class and add 
postsValues
 field:
private
 val postsValues = 
MutableLiveData
<
List
<
Post
>>()
You'll use 
LiveData
 to notify the observers about post changes.
Next, add 
postsValueEventListener
 field:
private
 lateinit 
var
 postsValueEventListener: 
ValueEventListener
This where you'll store your event listener.
Next, add the following function:
private
 
fun
 
listenForPostsValueChanges
()
 { 
    
//1
 
    postsValueEventListener = 
object
 : ValueEventListener { 
      
//2
 
      
override
 
fun
 
onCancelled
(databaseError: DatabaseError)
 { 
        
/* No op */
 
      } 
 
      
//3
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
218


      
override
 
fun
 
onDataChange
(dataSnapshot: DataSnapshot)
 { 
        
//4
 
        
if
 (dataSnapshot.exists()) { 
          
val
 posts = dataSnapshot.children.mapNotNull 
{ it.getValue(Post::
class
.
java
) }.
toList
() 
          postsValues.postValue(posts) 
        } 
else
 { 
          
//5
 
          postsValues.postValue(emptyList()) 
        } 
      } 
    } 
 
    
//6
 
    database.getReference(POSTS_REFERENCE) 
        .addValueEventListener(postsValueEventListener) 
}
1. You add 
ValueEventListener
 as an anonymous inner class and you assign it to 
postsValueEventListener
 field. There are two methods that you need to 
implement.
2. The 
onCancelled(databaseError: DatabaseError)
 method gets triggered if 
reading from the database is cancelled. Reading can be canceled in case if there 
are server issues or if you don't have access to the location you're trying to read 
from due to database rules. 
databaseError
 parameter contains more 
information about an error that occurred. In this case, you won't do anything if 
reading gets canceled.
3.
onDataChange(dataSnapshot: DataSnapshot)
 gets triggered whenever data 
under the reference you attached the listener to gets changed; either new data is 
added or existing data is updated or deleted. This is the method where you 
perform desired operations on the new data. You get the data back as 
DataSnapshot

DataSnapshot
 contains all the data from a specific location in 
the database. 
DataSnapshot
 is just an immutable copy of your database data so 
can't use it to modify the data in the database.
4. By calling the  
exists()
 method on 
DataSnapshot
 you check if the snapshot 
contains a non-null value. If there is data in the snapshot you get all of the direct 
children of the snapshot and you map each one to the 
Post
 object by calling the 
getValue(Post::class.java)
 method on a child. 
getValue(Post::class.java)
 wraps the data to the specified 
Post
 class and 
returns an instance of the passed in class or null if there is no data in this 
location. Then you add 
Post
 instances to the list and you set this list to the 
LiveData
 field created earlier which will notify all active observers about new 
data.
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
219


5. If data doesn't exist you set empty list as the new value of 
LiveData
. This is 
needed in the case where all posts get deleted and the database is empty. In that 
case, 
dataSnapshot.exists()
 will return 
false
 and by setting empty list as the 
new value you'll reflect that.
6. You attach the listener to the 
POSTS_REFERENCE
 because that is the location from 
where you want to listen for changes.
Now add 
onPostsValuesChange()
 function which just calls the function that 
attaches the listener and returns 
LiveData
 field:
fun
 
onPostsValuesChange
()
: LiveData> { 
    listenForPostsValueChanges() 
    
return
 postsValues 
}
You only want to listen for posts updates when you're on the home screen. Once you 
navigate away from home screen you don't care about posts updates anymore. To 
achieve that you need to remove event listener when you're no longer interested in 
the events. Add 
removePostsValuesChangesListener()
 function:
fun
 
removePostsValuesChangesListener
()
 { 
    
database.getReference(POSTS_REFERENCE).removeEventListener(posts
ValueEventListener) 
}
This method removes the passed in event listener, by calling 
removeEventListener
 
function, from the specified location.
Open 
HomeActivity
 and add 
onPostsUpdate(posts: List
)
 function which 
will get called every time posts update and it will set new data to the recycler view 
adapter:
private
 
fun
 
onPostsUpdate
(posts: List
)
 { 
    feedAdapter.onFeedUpdate(posts) 
}
Now implement 
listenForPostsUpdates()
 function which will listen for the 
changes in the posts and will call 
onPostsUpdate()
 on every update. Replace the 
//
TODO
 comment with the following :
realtimeDatabaseManager.onPostsValuesChange() 
  .observe(
this
, Observer(::onPostsUpdate))
Finally, override 
onStop()
 method and call the
Saving Data on Android
Chapter 13: Reading to & Writing from Realtime Database
raywenderlich.com
220


realtimeDatabaseManager.removePostsValuesChangesListener()
 to stop 
listening for the posts updates:
override
 
fun
 
onStop
()
 { 
    
super
.onStop() 
    realtimeDatabaseManager.removePostsValuesChangesListener() 
}
Build and run your app. You should see the post that you previously added on the 
home screen:
Build and run your app once again on a different device and log in with a different 
account. Add a new post and observe on your first device how the data is updated in 
the realtime.

Download 19,28 Mb.

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