From 2aa3d6c49c6ea15a5aa4561c194985386bcff960 Mon Sep 17 00:00:00 2001 From: bastien ollier Date: Fri, 7 Apr 2023 17:26:32 +0200 Subject: [PATCH] add ViewModel --- app/build.gradle | 7 +++-- .../fr/iut/mapping/RestaurantViewModel.kt | 26 +++++++++++++++++++ .../main/res/layout/fragment_likes_page.xml | 4 +-- 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 app/src/main/java/fr/iut/mapping/RestaurantViewModel.kt diff --git a/app/build.gradle b/app/build.gradle index 573053c..73d1808 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -46,8 +46,8 @@ dependencies { implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation "com.squareup.retrofit2:converter-moshi:2.9.0" implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2-native-mt' - implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0' + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4' + implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.1' implementation 'androidx.fragment:fragment-ktx:1.5.6' implementation 'androidx.appcompat:appcompat:1.6.1' @@ -58,6 +58,9 @@ dependencies { kapt 'androidx.room:room-compiler:2.5.1' implementation 'androidx.room:room-ktx:2.5.1' + implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.6.1" + + testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' diff --git a/app/src/main/java/fr/iut/mapping/RestaurantViewModel.kt b/app/src/main/java/fr/iut/mapping/RestaurantViewModel.kt new file mode 100644 index 0000000..1bf1357 --- /dev/null +++ b/app/src/main/java/fr/iut/mapping/RestaurantViewModel.kt @@ -0,0 +1,26 @@ +package fr.iut.mapping + +import androidx.lifecycle.* +import fr.iut.mapping.database.Entity.RestaurantEntity +import fr.iut.mapping.database.RestaurantRepository +import kotlinx.coroutines.launch + +class RestaurantViewModel(private val repository: RestaurantRepository): ViewModel() { + val restaurantLikes: LiveData> = repository.restaurantLikes.asLiveData() + + fun insert(restaurant: RestaurantEntity) = viewModelScope.launch { + repository.insert(restaurant) + } + +} + +class RestaurantViewModelFactory(private val repository: RestaurantRepository) : ViewModelProvider.Factory{ + override fun create(modelClass: Class): T { + if (modelClass.isAssignableFrom(RestaurantViewModel::class.java)) { + @Suppress("UNCHECKED_CAST") + return RestaurantViewModel(repository) as T + } + throw IllegalArgumentException("Unknown ViewModel class") + } + +} \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_likes_page.xml b/app/src/main/res/layout/fragment_likes_page.xml index baf836a..838281e 100644 --- a/app/src/main/res/layout/fragment_likes_page.xml +++ b/app/src/main/res/layout/fragment_likes_page.xml @@ -2,10 +2,8 @@ + android:layout_height="match_parent"> -