Saving Data on Android


Utils.kt  under the root package. Open  MainActivity.kt



Download 19,28 Mb.
Pdf ko'rish
bet175/292
Sana24.01.2022
Hajmi19,28 Mb.
#407089
1   ...   171   172   173   174   175   176   177   178   ...   292
Bog'liq
Bailey J., Dominguez A., Djermanovic D. - Saving Data on Android (1st Edition) - 2019

Utils.kt
 under the root package.
Open 
MainActivity.kt
 and add the following property at the top of your class:
private
 
val
 viewModel 
by
 lazy { getViewModel 
{ MainViewModel(Repository()) } }
The above code uses lazy initialization to create your 
MainViewModel
 using 
getViewModel()
 which automatically takes care of the initialization and creation 
logic of the 
ViewModel
s using a 
ViewModelFactory
.
Next, you need to set up menu actions for the user:
private
 
fun
 
prepopulateQuestions
()
 = 
viewModel.prepopulateQuestions() 
// 1
 
 
private
 
fun
 
clearQuestions
()
 = viewModel.clearQuestions() 
// 2
 
 
override
 
fun
 
onOptionsItemSelected
(item: MenuItem)

Boolean
 { 
// 
3
 
  
when
 (item.itemId) { 
    R.id.prepopulate -> prepopulateQuestions() 
    R.id.clear -> clearQuestions() 
    
else
 -> toast(
"error"

  } 
  
return
 
super
.onOptionsItemSelected(item) 
}
Step by step:
1.
prepopulateQuestions()
 uses your 
viewModel
 to prepopulate your Room 
database with sample question and answer records.
2.
clearQuestions()
 uses your 
viewModel
 to clear all the rows in your database.
3. Here, you are adding the appropriate actions to your 
Activity
's action bar. If the 
user taps on the 

Download 19,28 Mb.

Do'stlaringiz bilan baham:
1   ...   171   172   173   174   175   176   177   178   ...   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