Saving Data on Android


viewmodel  package and name it  QuizViewModel



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

viewmodel
 package and name it 
QuizViewModel

Modify your class like below:
class
 
QuizViewModel
(repository: QuizRepository) : ViewModel() { 
}
Just like before, you are making the 
QuizViewModel
 class extend from 
ViewModel()
 
and have the repository property in the primary constructor.
Next, add the following properties to the top of your class:
private
 
val
 questionAndAnswers = 
MediatorLiveData() 
// 1
 
private
 
val
 currentQuestion = MutableLiveData<
Int
>() 
// 2
 
private
 
val
 currentState = MediatorLiveData() 
// 3
 
private
 
val
 allQuestionAndAllAnswers = 
repository.getQuestionAndAllAnswers() 
// 4
 
private
 
var
 score: 
Int
 = 
0
 
// 5
Step by step:
1. Represents the current 
QuestionAndAnswers
 that is going to be sent to 
QuestionActivity
 and displayed to the user.
2.
currentQuestion
 is a helper property that helps you keep track of which 
question has to be displayed from the list of questions retrieved from the 
repository. For example, if 
currentQuestion
 is equal to 0 you are going to 
display the question with 
question_id = 0
.
3.
currentState
 contains the current 
QuizState
 that is going to be updated by 
your ViewModel and observed by your 
QuestionActivity
.
4.
allQuestionAndAllAnswers
 contains a 
LiveData
 list of all the questions in your 
database.
5.
score
 is another helper that holds the score of your user which is updated each 
time your user answers a question correctly.
Saving Data on Android Chapter 9: Using Room with Google's Architecture Components
raywenderlich.com
159


Next, add the following methods:
fun
 
getCurrentState
()
: LiveData = currentState 
 
private
 
fun
 
changeCurrentQuestion
()
 { 
  currentQuestion.postValue(currentQuestion.value?.inc()) 
}
getCurrentState()
 will be used by your 
MainActivity
 to retrieve and observe the 
current 
QuizState

changeCurrentQuestion()
 simply adds one to the value of 
currentQuestion
.
Next, add the following method:
private
 
fun
 
addStateSources
()
 { 
  currentState.addSource(currentQuestion) 
{ currentQuestionNumber -> 
// 1
 
    
if
 (currentQuestionNumber == 
allQuestionAndAllAnswers.value?.size) { 
      
currentState.postValue(QuizState.Finish(currentQuestionNumber, 
score)) 
    } 
  } 
  currentState.addSource(allQuestionAndAllAnswers) 
{ allQuestionsAndAnswers -> 
// 2
 
    
if
 (allQuestionsAndAnswers.isEmpty()) { 
      currentState.postValue(QuizState.Empty) 
    } 
  } 
  currentState.addSource(questionAndAnswers) 
{ questionAndAnswers -> 
// 3
 
    currentState.postValue(QuizState.Data(questionAndAnswers)) 
  } 
}
You will call 
addStateSources()
 to add the sources which your 
currentState
 
needs to observe: 
currentQuestion

allQuestionAndAllAnswers
 and 
questionAndAnswers
.  Taking each commented section in turn:
1. If 
currentQuestion
 is equal to the number of questions in your database it 
means that your user has finished answering the questions in your quiz, so you 
will change the value of 
QuizState
 to 
Finish
.
2. If the list of questions retrieved from the database is empty you will change the 
value of 
QuizState
 to 
Empty
.
3. This is the 
questionAndAnswers
 that you will send to the 
QuestionActivity
 in 
Data
.
Saving Data on Android Chapter 9: Using Room with Google's Architecture Components
raywenderlich.com
160


Now, add the following method:
private
 
fun
 
addQuestionSources
()
 { 
  questionAndAnswers.addSource(currentQuestion) 
{ currentQuestionNumber -> 
    
val
 questions = allQuestionAndAllAnswers.value 
       
    
if
 (questions != 
null
 && currentQuestionNumber < 
questions.size) { 
      
questionAndAnswers.postValue(questions[currentQuestionNumber]) 
    } 
  } 
     
  questionAndAnswers.addSource(allQuestionAndAllAnswers) 
{ questionsAndAnswers -> 
    
val
 currentQuestionNumber = currentQuestion.value  
       
    
if
 (currentQuestionNumber != 
null
 && 
questionsAndAnswers.isNotEmpty()) {  
      
questionAndAnswers.postValue(questionsAndAnswers[currentQuestion
Number]) 
    } 
  } 
}
This method adds two different sources to your 
questionAndAnswers

currentQuestion
 and 
allQuestionAndAllAnswers
. Observing 
currentQuestion
 
will help you update the current 
allQuestionAndAllAnswers
 that will be sent to the 
QuestionActivity
 using a 
Data
. Observing 
allQuestionAndAllAnswers
 will tell 
your 
questionAndAnswers
 when the list of questions has been properly retrieved 
from your database.
Now, add the following code:
fun
 
nextQuestion
(choice: Int)
 { 
// 1
 
  verifyAnswer(choice) 
  changeCurrentQuestion() 

 
private
 
fun
 
verifyAnswer
(choice: Int)
 { 
// 2
 
  
val
 currentQuestion = questionAndAnswers.value 
 
  
if
 (currentQuestion != 
null
 && 
currentQuestion.answers[choice].isCorrect) { 
    score++ 
  } 
}
Saving Data on Android Chapter 9: Using Room with Google's Architecture Components
raywenderlich.com
161


Step by step:
1. This method will be called when the user presses the 
NEXT
 button and will call 
verifyAnswer()
 and 
changeCurrentQuestion()
.
2.
verifyAnswer()
 checks if the answer selected by the user is correct and will 
increase the 
score
 accordingly.
Finally, add the following 
init
 block, under your class properties, to set up your 
ViewModel
:
init
 { 
  currentState.postValue(
QuizState
.
Loading

  addStateSources() 
  addQuestionSources() 
  currentQuestion.postValue(
0

}
Here, you are initializing the 
QuizState
 as 
Loading
 and 
currentQuestion
 with a 
value of zero (
0
). You are also calling 
addStateSources()
 and 
addQuestionSources()
 as soon as your 

Download 19,28 Mb.

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