diff --git a/app/src/main/java/com/example/plainolnotes4/MainFragment.kt b/app/src/main/java/com/example/plainolnotes4/MainFragment.kt index 561160f..11f1632 100644 --- a/app/src/main/java/com/example/plainolnotes4/MainFragment.kt +++ b/app/src/main/java/com/example/plainolnotes4/MainFragment.kt @@ -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 @@ -62,7 +62,8 @@ class MainFragment : Fragment(), } private fun addSampleData(): Boolean { - TODO("Not yet implemented") + viewModel.addSampleData() + return true } override fun onItemClick(noteId: Int) { diff --git a/app/src/main/java/com/example/plainolnotes4/MainViewModel.kt b/app/src/main/java/com/example/plainolnotes4/MainViewModel.kt index 109f58a..b4e4917 100644 --- a/app/src/main/java/com/example/plainolnotes4/MainViewModel.kt +++ b/app/src/main/java/com/example/plainolnotes4/MainViewModel.kt @@ -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>() + 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) + } + } } + } \ No newline at end of file diff --git a/app/src/main/java/com/example/plainolnotes4/data/SampleDataProvider.kt b/app/src/main/java/com/example/plainolnotes4/data/SampleDataProvider.kt index e6f208a..b553857 100644 --- a/app/src/main/java/com/example/plainolnotes4/data/SampleDataProvider.kt +++ b/app/src/main/java/com/example/plainolnotes4/data/SampleDataProvider.kt @@ -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) ) }