Skip to content

Commit

Permalink
05_02e
Browse files Browse the repository at this point in the history
  • Loading branch information
davidgassner committed Jul 23, 2020
1 parent 91ca3a2 commit 641c4a5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
5 changes: 3 additions & 2 deletions app/src/main/java/com/example/plainolnotes4/MainFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class MainFragment : Fragment(),
addItemDecoration(divider)
}

viewModel.notesList.observe(viewLifecycleOwner, Observer {
viewModel.notesList?.observe(viewLifecycleOwner, Observer {
Log.i("noteLogging", it.toString())
adapter = NotesListAdapter(it, this@MainFragment)
binding.recyclerView.adapter = adapter
Expand All @@ -62,7 +62,8 @@ class MainFragment : Fragment(),
}

private fun addSampleData(): Boolean {
TODO("Not yet implemented")
viewModel.addSampleData()
return true
}

override fun onItemClick(noteId: Int) {
Expand Down
22 changes: 18 additions & 4 deletions app/src/main/java/com/example/plainolnotes4/MainViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
package com.example.plainolnotes4

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.plainolnotes4.data.AppDatabase
import com.example.plainolnotes4.data.NoteEntity
import com.example.plainolnotes4.data.SampleDataProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainViewModel : ViewModel() {
class MainViewModel(app: Application) : AndroidViewModel(app) {

val notesList = MutableLiveData<List<NoteEntity>>()
private val database = AppDatabase.getInstance(app)
val notesList = database?.noteDao()?.getAll()

init {
notesList.value = SampleDataProvider.getNotes()
fun addSampleData() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val sampleNotes = SampleDataProvider.getNotes()
database?.noteDao()?.insertAll(sampleNotes)
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ class SampleDataProvider {
}

fun getNotes() = arrayListOf(
NoteEntity(1, getDate(0), sampleText1),
NoteEntity(2, getDate(1), sampleText2),
NoteEntity(3, getDate(2), sampleText3)
NoteEntity(getDate(0), sampleText1),
NoteEntity(getDate(1), sampleText2),
NoteEntity(getDate(2), sampleText3)
)

}
Expand Down

0 comments on commit 641c4a5

Please sign in to comment.