Лаб 3. Всё есть, но есть и проблемы

This commit is contained in:
Kate 2023-11-23 11:19:13 +04:00
parent 17754f6e72
commit a20931c7d5
41 changed files with 624 additions and 332 deletions

Binary file not shown.

View File

@ -1,2 +0,0 @@
#Sun Oct 08 15:55:30 GMT+04:00 2023
gradle.version=8.0

Binary file not shown.

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="Kotlin2JvmCompilerArguments"> <component name="Kotlin2JvmCompilerArguments">
<option name="jvmTarget" value="11" /> <option name="jvmTarget" value="17" />
</component> </component>
<component name="KotlinJpsPluginSettings"> <component name="KotlinJpsPluginSettings">
<option name="version" value="1.8.20" /> <option name="version" value="1.8.20" />

View File

@ -9,33 +9,55 @@
<option name="autoReloadType" value="NONE" /> <option name="autoReloadType" value="NONE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="dc3793c7-c725-42e8-8eda-044c95f334c1" name="Changes" comment="Лаб 3 создание моделей"> <list default="true" id="dc3793c7-c725-42e8-8eda-044c95f334c1" name="Changes" comment="Лаб 3 изменение действий под новые модели. Начало">
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt" afterDir="false" /> <change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/UserWithPets.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt" afterDir="false" /> <change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/PetViewModel.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/checksums/checksums.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/checksums/checksums.lock" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/checksums/checksums.lock" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/checksums/md5-checksums.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/checksums/md5-checksums.bin" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/checksums/md5-checksums.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/checksums/sha1-checksums.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/checksums/sha1-checksums.bin" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/checksums/sha1-checksums.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/dependencies-accessors/dependencies-accessors.lock" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/dependencies-accessors/gc.properties" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileChanges/last-build.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/resourceHashesCache.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/gc.properties" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/cache.properties" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/file-system.probe" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/vcs-1/gc.properties" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/kotlinc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/kotlinc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/build.gradle.kts" beforeDir="false" afterPath="$PROJECT_DIR$/app/build.gradle.kts" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/build.gradle.kts" beforeDir="false" afterPath="$PROJECT_DIR$/app/build.gradle.kts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Login.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Login.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Login.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Login.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/PetDao.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/PetDao.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/AuthViewModel.kt" beforeDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/User.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/User.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/User.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/User.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" /> <option name="LAST_RESOLUTION" value="IGNORE" />
</component> </component>
<component name="ExecutionTargetManager" SELECTED_TARGET="device_and_snapshot_combo_box_target[C:\Users\Kate\.android\avd\Pixel_3a_API_34_extension_level_7_x86_64.avd]" /> <component name="ExecutionTargetManager" SELECTED_TARGET="device_and_snapshot_combo_box_target[RF8N601QWVE]" />
<component name="ExternalProjectsData"> <component name="ExternalProjectsData">
<projectState path="$PROJECT_DIR$"> <projectState path="$PROJECT_DIR$">
<ProjectState /> <ProjectState />
@ -49,30 +71,7 @@
</task> </task>
<projects_view> <projects_view>
<tree_state> <tree_state>
<expand> <expand />
<path>
<item name="" type="6a2764b6:ExternalProjectsStructure$RootNode" />
<item name="PMUapp" type="f1a62948:ProjectNode" />
</path>
<path>
<item name="" type="6a2764b6:ExternalProjectsStructure$RootNode" />
<item name="PMUapp" type="f1a62948:ProjectNode" />
<item name="app" type="2d1252cf:ModuleNode" />
</path>
<path>
<item name="" type="6a2764b6:ExternalProjectsStructure$RootNode" />
<item name="PMUapp" type="f1a62948:ProjectNode" />
<item name="app" type="2d1252cf:ModuleNode" />
<item name="Tasks" type="e4a08cd1:TasksNode" />
</path>
<path>
<item name="" type="6a2764b6:ExternalProjectsStructure$RootNode" />
<item name="PMUapp" type="f1a62948:ProjectNode" />
<item name="app" type="2d1252cf:ModuleNode" />
<item name="Tasks" type="e4a08cd1:TasksNode" />
<item name="other" type="c8890929:TasksNode$1" />
</path>
</expand>
<select /> <select />
</tree_state> </tree_state>
</projects_view> </projects_view>
@ -118,8 +117,11 @@
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;, &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.cidr.known.project.marker&quot;: &quot;true&quot;, &quot;RunOnceActivity.cidr.known.project.marker&quot;: &quot;true&quot;,
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;, &quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;android-custom-viewC:/Users/Kate/AppData/Local/Android/Sdk/sources/android-31/android/view/View.java_SELECTED&quot;: &quot;View&quot;,
&quot;android-custom-viewC:/Users/Kate/AppData/Local/Android/Sdk/sources/android-31/android/view/ViewGroup.java_SELECTED&quot;: &quot;ViewGroup&quot;,
&quot;cidr.known.project.marker&quot;: &quot;true&quot;, &quot;cidr.known.project.marker&quot;: &quot;true&quot;,
&quot;com.android.tools.idea.devicemanager.tab&quot;: &quot;Physical&quot;, &quot;com.android.tools.idea.devicemanager.tab&quot;: &quot;Physical&quot;,
&quot;com.google.services.firebase.aqiPopupShown&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;C:/Users/Kate/AndroidStudioProjects/Ihonkina_PIbd-31_PMU&quot;, &quot;last_opened_file_path&quot;: &quot;C:/Users/Kate/AndroidStudioProjects/Ihonkina_PIbd-31_PMU&quot;,
&quot;project.structure.last.edited&quot;: &quot;Modules&quot;, &quot;project.structure.last.edited&quot;: &quot;Modules&quot;,
&quot;project.structure.proportion&quot;: &quot;0.17&quot;, &quot;project.structure.proportion&quot;: &quot;0.17&quot;,
@ -304,7 +306,14 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1699816471908</updated> <updated>1699816471908</updated>
</task> </task>
<option name="localTasksCounter" value="12" /> <task id="LOCAL-00012" summary="Лаб 3 изменение действий под новые модели. Начало">
<created>1699890169920</created>
<option name="number" value="00012" />
<option name="presentableId" value="LOCAL-00012" />
<option name="project" value="LOCAL" />
<updated>1699890169920</updated>
</task>
<option name="localTasksCounter" value="13" />
<servers /> <servers />
</component> </component>
<component name="Vcs.Log.Tabs.Properties"> <component name="Vcs.Log.Tabs.Properties">
@ -341,6 +350,41 @@
<MESSAGE value="Лаб 2 вроде конец" /> <MESSAGE value="Лаб 2 вроде конец" />
<MESSAGE value="Лаб 3 начало" /> <MESSAGE value="Лаб 3 начало" />
<MESSAGE value="Лаб 3 создание моделей" /> <MESSAGE value="Лаб 3 создание моделей" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 3 создание моделей" /> <MESSAGE value="Лаб 3 изменение действий под новые модели. Начало" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 3 изменение действий под новые модели. Начало" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints>
<line-breakpoint enabled="true" type="kotlin-line">
<url>file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt</url>
<line>31</line>
<properties>
<option name="lambda-ordinal" value="-1" />
</properties>
<option name="timeStamp" value="81" />
</line-breakpoint>
<line-breakpoint enabled="true" type="kotlin-line">
<url>file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt</url>
<line>27</line>
<option name="timeStamp" value="82" />
</line-breakpoint>
<line-breakpoint enabled="true" type="kotlin-line">
<url>file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt</url>
<line>28</line>
<option name="timeStamp" value="83" />
</line-breakpoint>
<line-breakpoint enabled="true" type="kotlin-line">
<url>file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt</url>
<line>108</line>
<option name="timeStamp" value="84" />
</line-breakpoint>
<line-breakpoint enabled="true" type="kotlin-line">
<url>file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt</url>
<line>217</line>
<option name="timeStamp" value="88" />
</line-breakpoint>
</breakpoints>
</breakpoint-manager>
</component> </component>
</project> </project>

View File

@ -31,11 +31,11 @@ android {
} }
} }
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_11 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_17
} }
kotlinOptions { kotlinOptions {
jvmTarget = "11" jvmTarget = "17"
} }
buildFeatures { buildFeatures {
compose = true compose = true
@ -87,4 +87,9 @@ dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4") androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling") debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest") debugImplementation("androidx.compose.ui:ui-test-manifest")
implementation("androidx.compose.runtime:runtime-livedata:1.1.0-alpha03")
implementation("androidx.compose.runtime:runtime-livedata:1.1.0-alpha03")
} }

View File

@ -12,12 +12,13 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.pmuapp.R import com.example.pmuapp.R
import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.Pet import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.User import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) { fun CreatePet(navController: NavController, authViewModel: AuthViewModel, onSaveClick: (Pet) -> Unit) {
var selectedImage by remember { mutableStateOf(R.drawable.pet1) } var selectedImage by remember { mutableStateOf(R.drawable.pet1) }
var petName by remember { mutableStateOf("") } var petName by remember { mutableStateOf("") }
@ -70,12 +71,13 @@ fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) {
Button( Button(
onClick = { onClick = {
if (petName.isNotEmpty()) { if (petName.isNotEmpty()) {
val newPet = Pet(0, petName, selectedImage, "") val newPet = Pet(petName, selectedImage, "", authViewModel.currentUser.value )
onSaveClick(newPet) onSaveClick(newPet)
petName = "" petName = ""
selectedImage = R.drawable.pet1 selectedImage = R.drawable.pet1
navController.popBackStack() navController.navigate(Screen.Home.route)
} }
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()

View File

@ -28,18 +28,18 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@RequiresApi(VERSION_CODES.O) @RequiresApi(VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) { fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, pet : Pet?, onSaveClick: (Pet) -> Unit) {
val pet = (authViewModel.currentUser?.petId ?: emptyList()).find { it.id == petId }
var petName by remember { mutableStateOf(pet?.name ?: "") } var petName = remember { mutableStateOf(pet?.name ?: "") }
var petNotes by remember { mutableStateOf(pet?.notes ?: "") } var petNotes = remember { mutableStateOf(pet?.notes ?: "") }
Column( Column(
modifier = Modifier modifier = Modifier
@ -47,6 +47,7 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
.padding(10.dp), .padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
if(pet!=null) {
val imageResId = pet?.imageResId ?: 0 val imageResId = pet?.imageResId ?: 0
Image( Image(
painter = painterResource(id = imageResId), painter = painterResource(id = imageResId),
@ -55,10 +56,11 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
.fillMaxWidth() .fillMaxWidth()
.height(200.dp) .height(200.dp)
) )
}
OutlinedTextField( OutlinedTextField(
value = petName, value = petName.value,
onValueChange = { petName = it }, onValueChange = { petName.value = it },
label = { Text("Имя питомца") }, label = { Text("Имя питомца") },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@ -72,8 +74,8 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
) )
TextField( TextField(
value = petNotes, value = petNotes.value,
onValueChange = { petNotes = it }, onValueChange = { petNotes.value = it },
label = { Text("Заметки") }, label = { Text("Заметки") },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@ -86,17 +88,26 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
Spacer(modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.weight(1f))
val editedPetId = Screen.PlayPet.route.replace("{id}", pet?.id.toString())
val petId = Screen.PlayPet.route.replace(
"{id}",
pet?.id.toString()
)
Button( Button(
onClick = { onClick = {
val updatedPet = pet?.copy(name = petName, notes = petNotes) ?: return@Button val updatedPet = Pet(
pet?.id ?: 0,
petName.value,
pet?.imageResId ?:0,
pet?.userId ?:0,
petNotes.value)
onSaveClick(updatedPet)
// val petId = Screen.EditPet.route.replace("{id}", pet?.id.toString())
// navController?.navigate(petId)
//navController.navigate()
navController.navigate(Screen.Home.route)
petViewModel.updatePet(updatedPet)
userViewModel.updatePetOnUser(authViewModel.currentUser?.id ?: -1, updatedPet)
authViewModel.currentUser=userViewModel.getUser(authViewModel.currentUser?.id ?: -1)
val petId = Screen.EditPet.route.replace("{id}", pet.id.toString())
navController?.navigate(editedPetId)
}, },
modifier = Modifier.padding(16.dp) modifier = Modifier.padding(16.dp)
) { ) {

View File

@ -1,11 +1,13 @@
package com.example.pmuapp.composeui package com.example.pmuapp.composeui
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
@ -15,9 +17,10 @@ import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.composeui.PetList import com.example.pmuapp.models.user.composeui.PetList
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("RememberReturnType")
@Composable @Composable
fun Home(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel) { fun Home(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel) {
Column( Column(
@ -34,7 +37,7 @@ fun Home(navController: NavController, authViewModel: AuthViewModel, petViewMode
} }
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
PetList(navController,authViewModel, petViewModel, userViewModel, authViewModel.currentUser?.id ?: -1) PetList(navController,authViewModel, petViewModel, userViewModel, authViewModel.currentUser.value?.id ?: -1)
} }
} }

View File

@ -12,6 +12,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextField import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@ -21,9 +22,12 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@ -34,7 +38,6 @@ fun Login(
var username by remember { mutableStateOf("") } var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") } var password by remember { mutableStateOf("") }
val users by authViewModel.currentUser.collectAsState()
Column( Column(
modifier = Modifier modifier = Modifier
@ -66,24 +69,25 @@ fun Login(
Button( Button(
onClick = { onClick = {
val authenticatedUser = authViewModel.loginUser(username, password) authViewModel.viewModelScope.launch {
if (authenticatedUser != null) { authViewModel.loginUser(username, password)
// Аутентификация успешна
navController.navigate(Screen.Profile.route)
} else {
// Аутентификация не удалась
println("Authentication failed")
} }
// Добавляем небольшую задержку (например, 100 мс) для обеспечения завершения операции входа в систему
// delay(1000)
val authenticatedUser = authViewModel.currentUser.value
if (authenticatedUser != null) {
navController.navigate(Screen.Home.route)
} else {
println("Аутентификация не удалась")
}
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
Text("Login") Text("Login")
} }
// Вы можете также использовать users для дополнительных проверок или вывода информации
users?.let {
Text("Current User: ${it.name}")
}
} }
} }

View File

@ -24,15 +24,15 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@RequiresApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) { fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, pet: Pet?) {
val pet = (authViewModel.currentUser?.petId ?: emptyList()).find { it.id == petId }
Column( Column(
modifier = Modifier modifier = Modifier
@ -40,6 +40,7 @@ fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewM
.padding(10.dp), .padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
if (pet!=null) {
val imageResId = pet?.imageResId ?: 0 val imageResId = pet?.imageResId ?: 0
Image( Image(
painter = painterResource(id = imageResId), painter = painterResource(id = imageResId),
@ -48,7 +49,7 @@ fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewM
.fillMaxWidth() .fillMaxWidth()
.height(200.dp) .height(200.dp)
) )
}
Text( Text(
text = pet?.name ?: "", text = pet?.name ?: "",
style = TextStyle(fontWeight = FontWeight.Bold, fontSize = 24.sp), style = TextStyle(fontWeight = FontWeight.Bold, fontSize = 24.sp),

View File

@ -108,7 +108,6 @@ fun Profile(navController: NavController,currentUser: User?, onSaveClick: (User)
nameState.value, nameState.value,
loginState.value, loginState.value,
passwordState.value, passwordState.value,
currentUser?.pets ?: emptyList(),
selectedImageUri.value?.toString() ?: "" selectedImageUri.value?.toString() ?: ""
) )
onSaveClick(updatedUser) onSaveClick(updatedUser)

View File

@ -1,6 +1,7 @@
package com.example.pmuapp.composeui.navigation package com.example.pmuapp.composeui.navigation
import CreatePet import CreatePet
import android.annotation.SuppressLint
import android.os.Build import android.os.Build
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@ -24,7 +25,9 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavDestination import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavGraph.Companion.findStartDestination
@ -41,11 +44,17 @@ import com.example.pmuapp.composeui.Home
import com.example.pmuapp.composeui.Login import com.example.pmuapp.composeui.Login
import com.example.pmuapp.composeui.PlayPet import com.example.pmuapp.composeui.PlayPet
import com.example.pmuapp.composeui.Profile import com.example.pmuapp.composeui.Profile
import com.example.pmuapp.models.user.Dao.PetDao
import com.example.pmuapp.models.user.Dao.UserDao
import com.example.pmuapp.models.user.composeui.PetList import com.example.pmuapp.models.user.composeui.PetList
import com.example.pmuapp.models.user.composeui.UserList import com.example.pmuapp.models.user.composeui.UserList
import com.example.pmuapp.models.user.database.AppDatabase
import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@ -116,6 +125,7 @@ fun Navbar(
} }
} }
@SuppressLint("StateFlowValueCalledInComposition", "SuspiciousIndentation")
@RequiresApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O)
@Composable @Composable
fun NavHost( fun NavHost(
@ -131,17 +141,18 @@ fun NavHost(
modifier = Modifier.padding(innerPadding) modifier = Modifier.padding(innerPadding)
) { ) {
composable(Screen.Login.route) { composable(Screen.Login.route) {
Login(navController, authViewModel,userViewModel.getUsers()) Login(navController, authViewModel)
} }
composable(Screen.Profile.route) { composable(Screen.Profile.route) {
val currentUser = authViewModel.currentUser ?: userViewModel.getUsers().firstOrNull() val currentUser = authViewModel.currentUser.value
if (currentUser != null) { if (currentUser != null) {
Profile(navController, Profile(navController,
currentUser = currentUser , currentUser = currentUser ,
onSaveClick = {updatedUser -> onSaveClick = {updatedUser ->
userViewModel.updateUser(updatedUser) userViewModel.updateUser(updatedUser)
authViewModel.currentUser = updatedUser // authViewModel.updateCurrentUset(currentUser?.id ?:-1)
navController.navigate(Screen.Profile.route) navController.navigate(Screen.UserList.route)
} }
) )
} else { } else {
@ -149,13 +160,25 @@ fun NavHost(
} }
composable(Screen.UserList.route) { UserList(navController, userViewModel) } composable(Screen.UserList.route) { UserList(navController, userViewModel) }
composable(Screen.Home.route) { Home(navController, authViewModel,petViewModel,userViewModel) } composable(Screen.Home.route){
val currentUser = authViewModel.currentUser
if (currentUser != null) {
Home(navController,
authViewModel,
petViewModel,
userViewModel
)
} else {
}
}
composable(Screen.CreatePet.route) { composable(Screen.CreatePet.route) {
val currentUser = authViewModel.currentUser ?: userViewModel.getUsers().firstOrNull() val currentUser = authViewModel.currentUser
CreatePet ( navController, onSaveClick = { newPet -> val id: Int = currentUser.value?.id?.toInt() ?: 0
var adedPet = petViewModel.createPet(newPet) CreatePet ( navController, authViewModel , onSaveClick = { newPet ->
userViewModel.addPetToUser(currentUser?.id ?:0, adedPet) petViewModel.createPet(newPet)
authViewModel.currentUser = userViewModel.getUser(currentUser?.id ?:0) //userViewModel.addTask(currentUser?.id ?:0, adedTask)
// authViewModel.updateCurrentUset(id)
} }
) )
@ -171,7 +194,7 @@ fun NavHost(
contentAlignment = Alignment.TopCenter, contentAlignment = Alignment.TopCenter,
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize()
) { ) {
PetList(navController,authViewModel, petViewModel, userViewModel, userId) PetList(navController,authViewModel, petViewModel, userViewModel, userId+1)
} }
} }
composable( composable(
@ -179,16 +202,23 @@ fun NavHost(
arguments = listOf(navArgument("id") { type = NavType.IntType }) arguments = listOf(navArgument("id") { type = NavType.IntType })
) { backStackEntry -> ) { backStackEntry ->
val petId = backStackEntry.arguments?.getInt("id") ?: -1 val petId = backStackEntry.arguments?.getInt("id") ?: -1
val pet = petViewModel.getPet(petId)
PlayPet(navController,authViewModel, petViewModel, userViewModel, petId) PlayPet(navController,authViewModel, petViewModel, userViewModel, pet.value)
} }
composable( composable(
Screen.EditPet.route, Screen.EditPet.route,
arguments = listOf(navArgument("id") { type = NavType.IntType }) arguments = listOf(navArgument("id") { type = NavType.IntType })
) { backStackEntry -> ) { backStackEntry ->
val petId = backStackEntry.arguments?.getInt("id") ?: -1 val petId = backStackEntry.arguments?.getInt("id") ?: -1
EditPet(navController,authViewModel, petViewModel, userViewModel, petId) val pet = petViewModel.getPet(petId)
EditPet(navController,authViewModel, petViewModel, userViewModel, pet.value,
onSaveClick = {updatedPet ->
petViewModel.viewModelScope.launch {
delay(1000)
petViewModel.updatePet(updatedPet)
delay(1000)
// authViewModel.updateCurrentUset(id)
}})
} }
} }
@ -199,9 +229,13 @@ fun NavHost(
@Composable @Composable
fun MainNavbar() { fun MainNavbar() {
val navController = rememberNavController() val navController = rememberNavController()
val authViewModel = remember { AuthViewModel() } val context = LocalContext.current
val userViewModel =remember {UserViewModel() } val database: AppDatabase = AppDatabase.getInstance(context)
val petViewModel = remember {PetViewModel()} val userDao: UserDao = database.userDao()
val petDao: PetDao = database.petDao()
val authViewModel = remember { AuthViewModel(userDao) }
val userViewModel = remember { UserViewModel(userDao) }
val petViewModel = remember { PetViewModel(petDao) }
val navBackStackEntry by navController.currentBackStackEntryAsState() val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination val currentDestination = navBackStackEntry?.destination
val currentScreen = currentDestination?.route?.let { Screen.getItem(it) } val currentScreen = currentDestination?.route?.let { Screen.getItem(it) }

View File

@ -4,13 +4,12 @@ package com.example.pmuapp.models.user.Dao;
import androidx.room.Dao; import androidx.room.Dao;
import androidx.room.Delete; import androidx.room.Delete;
import androidx.room.Insert; import androidx.room.Insert;
import androidx.room.OnConflictStrategy
import androidx.room.Query; import androidx.room.Query;
import androidx.room.Transaction import androidx.room.Transaction
import androidx.room.Update; import androidx.room.Update;
import com.example.pmuapp.models.user.model.Pet import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.PetWithImage
import com.example.pmuapp.models.user.model.User;
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import java.util.List; import java.util.List;
@ -20,7 +19,8 @@ import java.util.List;
interface PetDao { interface PetDao {
@Query("SELECT * FROM pets") @Query("SELECT * FROM pets")
fun getAllPets(): Flow<List<Pet>> fun getAllPets(): Flow<List<Pet>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(pets: kotlin.collections.List<Pet>)
@Insert @Insert
suspend fun insertPet(pet: Pet) suspend fun insertPet(pet: Pet)
@ -29,8 +29,8 @@ interface PetDao {
@Delete @Delete
suspend fun deletePet(pet: Pet) suspend fun deletePet(pet: Pet)
@Query("select * from pets where pets.id = :uid ")
@Transaction suspend fun getOne(uid: Int):Pet
@Query("SELECT * FROM pets WHERE id = :petId") @Query("select * from pets where pets.user_id = :uid")
fun getPetWithImageById(petId: Int): Flow<PetWithImage?> suspend fun getByUid(uid: Int): kotlin.collections.List<Pet>
} }

View File

@ -1,24 +1,24 @@
package com.example.pmuapp.models.user.Dao //package com.example.pmuapp.models.user.Dao
//
import androidx.room.Dao //import androidx.room.Dao
import androidx.room.Delete //import androidx.room.Delete
import androidx.room.Insert //import androidx.room.Insert
import androidx.room.Query //import androidx.room.Query
import androidx.room.Update //import androidx.room.Update
import com.example.pmuapp.models.user.model.PetImage //import com.example.pmuapp.models.user.model.PetImage
import kotlinx.coroutines.flow.Flow //import kotlinx.coroutines.flow.Flow
//
@Dao //@Dao
interface PetImageDao { //interface PetImageDao {
@Insert // @Insert
suspend fun insertPetImage(petImage: PetImage) // suspend fun insertPetImage(petImage: PetImage)
//
@Update // @Update
suspend fun updatePetImage(petImage: PetImage) // suspend fun updatePetImage(petImage: PetImage)
//
@Delete // @Delete
suspend fun deletePetImage(petImage: PetImage) // suspend fun deletePetImage(petImage: PetImage)
//
@Query("SELECT * FROM pet_images WHERE pet_id = :petId") // @Query("SELECT * FROM pet_images WHERE pet_id = :petId")
fun getPetImagesByPetId(petId: Int): Flow<List<PetImage>> // fun getPetImagesByPetId(petId: Int): Flow<List<PetImage>>
} //}

View File

@ -5,17 +5,22 @@ import androidx.room.Dao;
import androidx.room.Delete; import androidx.room.Delete;
import androidx.room.Insert; import androidx.room.Insert;
import androidx.room.Query; import androidx.room.Query;
import androidx.room.Transaction
import androidx.room.Update; import androidx.room.Update;
import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.User; import com.example.pmuapp.models.user.model.User;
import com.example.pmuapp.models.user.model.UserWithPets
import kotlinx.coroutines.flow.Flow
import java.util.List; import java.util.List;
@Dao @Dao
interface UserDao { interface UserDao {
@Query("select * from users") @Transaction
suspend fun getAll(): List<User> @Query("SELECT * FROM users")
fun getUsersWithPets(): Flow<List<User>>
@Insert @Insert
suspend fun insert(user: User) suspend fun insert(user: User)
@ -26,9 +31,20 @@ interface UserDao {
@Delete @Delete
suspend fun delete(user: User) suspend fun delete(user: User)
@Query("SELECT * FROM users WHERE login = :login AND password = :password") // @Query("SELECT * FROM users left join pets on pets.user_id = users.id WHERE login = :login AND password = :password")
suspend fun getUserByLoginAndPassword(login: String, password: String): User? // suspend fun getUserByLoginAndPassword(login: String, password: String): UserWithPets
@Query("SELECT * FROM users WHERE id = :userId") @Query("SELECT * FROM users WHERE users.login = :username AND users.password = :password")
suspend fun getUserByLoginAndPassword(username: String, password: String): User?
// @Query("SELECT * FROM users WHERE id = :userId")
// suspend fun getUserWithPetsById(userId: Int): User?
@Transaction
@Query("SELECT * FROM users LEFT JOIN pets ON pets.user_id = users.id WHERE users.id = :userId")
suspend fun getUserById(userId: Int): User?
@Transaction
@Query("SELECT * FROM users LEFT JOIN pets ON pets.user_id = users.id WHERE users.id = :userId")
suspend fun getUserWithPetsById(userId: Int): User? suspend fun getUserWithPetsById(userId: Int): User?
} }

View File

@ -1,5 +1,6 @@
package com.example.pmuapp.models.user.composeui package com.example.pmuapp.models.user.composeui
import android.annotation.SuppressLint
import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@ -16,6 +17,8 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
@ -26,36 +29,38 @@ import androidx.compose.ui.unit.sp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@SuppressLint("StateFlowValueCalledInComposition")
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class) @OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
@Composable @Composable
fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, userId: Int) { fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, userId: Int) {
val currentUser = userViewModel.getUser(userId) val currentUser by userViewModel.user.collectAsState()
var pets = currentUser.petId // petViewModel.getPet(userId)
var pets = petViewModel.pets.collectAsState()
LazyColumn( LazyColumn(
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
if (userId != authViewModel.currentUser?.id ?: -1) { // if (authViewModel.currentUser.value?.id!=currentUser?.id) {
item { // item {
Text( // Text(
text = currentUser?.name + " (" + currentUser.login + ")", // text = currentUser?.name + " (" + currentUser?.login + ")",
style = TextStyle( // style = TextStyle(
fontSize = 24.sp, // fontSize = 24.sp,
fontWeight = FontWeight.Bold // fontWeight = FontWeight.Bold
), // ),
modifier = Modifier.padding(16.dp) // modifier = Modifier.padding(16.dp)
) // )
} // }
} // }
if (pets != null) {
item { items(pets.value.size) { index ->
FlowRow() { val pet = pets.value[index]
pets.forEach { pet ->
val imageId = pet.imageResId val imageId = pet.imageResId
val petName = pet.name val petName = pet.name
@ -74,12 +79,14 @@ fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewM
modifier = Modifier.padding(top = 4.dp) modifier = Modifier.padding(top = 4.dp)
) )
if (userId == authViewModel.currentUser?.id ?: -1) { if (userId ==(authViewModel.currentUser.value?.id ?: -1)) {
val petId = Screen.PlayPet.route.replace("{id}", pet.id.toString()) val petId = Screen.PlayPet.route.replace(
"{id}",
pet.id.toString()
)
Button( Button(
onClick = { onClick = {
navController?.navigate(petId) navController?.navigate(petId)
}, },
) { ) {
Text("Играть") Text("Играть")
@ -87,16 +94,6 @@ fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewM
IconButton( IconButton(
onClick = { onClick = {
petViewModel.deletePet(pet) petViewModel.deletePet(pet)
userViewModel.deletePet(
currentUser?.id
?: 0,
pet.id
)
authViewModel.currentUser =
userViewModel.getUser(
currentUser?.id
?: 0
)
} }
) { ) {
Icon( Icon(
@ -104,11 +101,10 @@ fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewM
contentDescription = "Удалить" contentDescription = "Удалить"
) )
} }
}
}
}
}
} }
} }
}
}
}
}
}

View File

@ -1,5 +1,6 @@
package com.example.pmuapp.models.user.composeui package com.example.pmuapp.models.user.composeui
import android.annotation.SuppressLint
import android.content.res.Configuration import android.content.res.Configuration
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@ -9,22 +10,25 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.User import com.example.pmuapp.models.user.model.User
import com.example.pmuapp.models.user.model.UserViewModel import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
import com.example.pmuapp.ui.theme.PMUappTheme import com.example.pmuapp.ui.theme.PMUappTheme
@SuppressLint("StateFlowValueCalledInComposition")
@Composable @Composable
fun UserList(navController: NavController?, userViewModel: UserViewModel) {
userViewModel.updateUsers()
var users = userViewModel.users.value
fun UserList(navController: NavController?, if (users.count()!=0) {
userViewModel: UserViewModel
) {
val users = userViewModel.users.value
Column(Modifier.padding(all = 10.dp)) { Column(Modifier.padding(all = 10.dp)) {
users.forEachIndexed() { index, user -> users.forEachIndexed() { index, user ->
val userId = Screen.UserView.route.replace("{id}", index.toString()) val userId = Screen.UserView.route.replace("{id}", index.toString())
@ -38,4 +42,5 @@ fun UserList(navController: NavController?,
} }
} }
} }
}

View File

@ -1,16 +1,15 @@
package com.example.pmuapp.models.user.database package com.example.pmuapp.models.user.database
import android.content.Context import android.content.Context
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.room.Database import androidx.room.Database
import androidx.room.Room import androidx.room.Room
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.pmuapp.R import com.example.pmuapp.R
import com.example.pmuapp.models.user.Dao.PetDao import com.example.pmuapp.models.user.Dao.PetDao
import com.example.pmuapp.models.user.Dao.PetImageDao
import com.example.pmuapp.models.user.Dao.UserDao import com.example.pmuapp.models.user.Dao.UserDao
import com.example.pmuapp.models.user.model.Pet import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.PetImage
import com.example.pmuapp.models.user.model.User import com.example.pmuapp.models.user.model.User
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@ -20,7 +19,7 @@ import kotlinx.coroutines.launch
abstract class AppDatabase : RoomDatabase() { abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao abstract fun userDao(): UserDao
abstract fun petDao(): PetDao abstract fun petDao(): PetDao
abstract fun petImageDao(): PetImageDao // abstract fun petImageDao(): PetImageDao
companion object { companion object {
private const val DB_NAME: String = "pmy-db" private const val DB_NAME: String = "pmy-db"
@ -31,23 +30,23 @@ abstract class AppDatabase : RoomDatabase() {
INSTANCE?.let { database -> INSTANCE?.let { database ->
// Groups // Groups
val userDao = database.userDao() val userDao = database.userDao()
val user1 = User(1, "Иван", "ivan", "111",R.drawable.avatar) val user1 = User(1, "Иван", "ivan", "111",R.drawable.avatar.toString())
val user2 = User(2, "Анна", "ann", "111",R.drawable.avatar) val user2 = User(2, "Анна", "ann", "111",R.drawable.avatar.toString())
val user3 = User(3, "Макс", "max", "111",R.drawable.avatar) val user3 = User(3, "Макс", "max", "111",R.drawable.avatar.toString())
userDao.insert(user1) userDao.insert(user1)
userDao.insert(user2) userDao.insert(user2)
userDao.insert(user3) userDao.insert(user3)
val petImageDao = database.petImageDao() // val petImageDao = database.petImageDao()
val petImage1 = PetImage(1, 1, R.drawable.pet1) // val petImage1 = PetImage(1, 1, R.drawable.pet1)
val petImage2 = PetImage(2, 2, R.drawable.pet2) // val petImage2 = PetImage(2, 2, R.drawable.pet2)
val petImage3 = PetImage(3, 3, R.drawable.pet3) // val petImage3 = PetImage(3, 3, R.drawable.pet3)
//
petImageDao.insertPetImage(petImage1) // petImageDao.insertPetImage(petImage1)
petImageDao.insertPetImage(petImage2) // petImageDao.insertPetImage(petImage2)
petImageDao.insertPetImage(petImage3) // petImageDao.insertPetImage(petImage3)
} }
} }

View File

@ -1,33 +1,38 @@
package com.example.pmuapp.models.user.model package com.example.pmuapp.models.user.model
import android.media.Image
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.room.ColumnInfo import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.ForeignKey import androidx.room.ForeignKey
import androidx.room.Ignore import androidx.room.Ignore
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import androidx.room.Relation
import com.example.pmuapp.R
import java.io.Serializable
@Entity(tableName = "pets") @Entity(
tableName = "pets", foreignKeys = [
ForeignKey(
entity = User::class,
parentColumns = ["id"],
childColumns = ["user_id"],
// onDelete = ForeignKey.CASCADE, // Set to CASCADE for automatic deletion of associated pets
// onUpdate = ForeignKey.CASCADE
)
]
)
data class Pet( data class Pet(
@PrimaryKey(autoGenerate = true) @PrimaryKey(autoGenerate = true)
val id: Int, val id: Int,
val name: String, val name: String,
@ColumnInfo(name = "image_res_id") @ColumnInfo(name = "image_res_id")
val imageResId: Int, val imageResId: Int,
@ColumnInfo(name = "user_id", index = true)
val userId: Int, // Changed from groupId to userId
val notes: String val notes: String
) { ) {
@Ignore @Ignore
constructor(name: String, imageResId: Int, notes: String) : constructor(name: String, imageResId: Int, notes: String, user: User?,) :
this(0, name, imageResId, notes) this(0, name, imageResId, user?.id ?:0, notes)
@Relation(parentColumn = "id", entityColumn = "pet_id") // @Relation(parentColumn = "id", entityColumn = "pet_id")
var petImage: PetImage? = null // var petImage: PetImage? = null
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return true if (this === other) return true

View File

@ -3,24 +3,24 @@ package com.example.pmuapp.models.user.model
import androidx.room.ColumnInfo import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
//
@Entity(tableName = "pet_images") //@Entity(tableName = "pet_images")
data class PetImage( //data class PetImage(
@PrimaryKey(autoGenerate = true) // @PrimaryKey(autoGenerate = true)
val id: Int, // val id: Int,
@ColumnInfo(name = "pet_id") // @ColumnInfo(name = "pet_id")
val petId: Int, // val petId: Int,
val imageData: Int // val imageData: Int
) { //) {
override fun equals(other: Any?): Boolean { // override fun equals(other: Any?): Boolean {
if (this === other) return true // if (this === other) return true
if (javaClass != other?.javaClass) return false // if (javaClass != other?.javaClass) return false
other as PetImage // other as PetImage
if (id != other.id) return false // if (id != other.id) return false
return true // return true
} // }
//
override fun hashCode(): Int { // override fun hashCode(): Int {
return id ?: -1 // return id ?: -1
} // }
} //}

View File

@ -3,11 +3,11 @@ package com.example.pmuapp.models.user.model
import androidx.room.Embedded import androidx.room.Embedded
import androidx.room.Relation import androidx.room.Relation
data class PetWithImage( //data class PetWithImage(
@Embedded val pet: Pet, // @Embedded val pet: Pet,
@Relation( // @Relation(
parentColumn = "id", // parentColumn = "id",
entityColumn = "pet_id" // entityColumn = "pet_id"
) // )
val petImage: PetImage? // val petImage: PetImage?
) //)

View File

@ -6,32 +6,24 @@ import androidx.room.Ignore
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import androidx.room.Relation import androidx.room.Relation
@Entity(tableName = "users") @Entity(tableName = "users")
data class User( data class User(
@PrimaryKey(autoGenerate = true) @PrimaryKey(autoGenerate = true)
val id: Int = 0, val id: Int = 0,
val name: String, val name: String = "",
val login: String, val login: String = "",
val password: String, val password: String = "",
@Relation(parentColumn = "id", entityColumn = "user_id")
var pets: List<Pet> = emptyList(),
val imageUri: String = "" val imageUri: String = ""
) { )
{
@Ignore @Ignore
constructor( constructor(
name: String, name: String,
login: String, login: String,
password: String, password: String,
pets: List<Pet>,
imageUri: String imageUri: String
) : this(0, name, login, password, pets, imageUri) ) : this(0, name, login, password, imageUri)
fun addPet(pet: Pet): User {
val updatedPets = pets.toMutableList()
updatedPets.add(pet)
return copy(pets = updatedPets)
}
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return true if (this === other) return true
if (javaClass != other?.javaClass) return false if (javaClass != other?.javaClass) return false

View File

@ -0,0 +1,14 @@
package com.example.pmuapp.models.user.model
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Relation
data class UserWithPets(
@Embedded val user: User,
@Relation(
parentColumn = "id",
entityColumn = "user_id"
)
val pets: List<Pet>
)

View File

@ -1,45 +1,55 @@
package com.example.pmuapp.models.user.model.viewmodel package com.example.pmuapp.models.user.model.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.example.pmuapp.models.user.Dao.UserDao import com.example.pmuapp.models.user.Dao.UserDao
import com.example.pmuapp.models.user.model.User import com.example.pmuapp.models.user.model.User
import com.example.pmuapp.models.user.model.UserWithPets
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
class AuthViewModel(private val userDao: UserDao) : ViewModel() { class AuthViewModel(private val userDao: UserDao) : ViewModel() {
private val _currentUser = MutableStateFlow<User?>(null) private val _currentUser = MutableStateFlow<User?>(null)
val currentUser: StateFlow<User?> get() = _currentUser.asStateFlow() val currentUser: StateFlow<User?> get() = _currentUser
init { /* init {
// Подписываемся на изменения в базе данных и обновляем _currentUser // Подписываемся на изменения в базе данных и обновляем _currentUser
viewModelScope.launch { viewModelScope.launch {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val users = userDao.getAll() val user = userDao.getUserByLoginAndPassword("", "")
// Ваш код обработки данных, если необходимо _currentUser.value = user
// Например, если вам нужно обновить _currentUser
_currentUser.value = users.firstOrNull()
} }
} }
} }
// Метод для входа пользователя */
fun loginUser(login: String, password: String) { fun loginUser(username: String, password: String) {
viewModelScope.launch { viewModelScope.launch {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val user = userDao.getUserByLoginAndPassword(login, password) val user = userDao.getUserByLoginAndPassword(username, password)
// Обновляем _currentUser после успешной аутентификации
_currentUser.value = user _currentUser.value = user
} }
} }
} }
fun updateCurrentUset(id:Int) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val user = userDao.getUserWithPetsById(id)
// Обновляем _currentUser после успешной аутентификации
_currentUser.value = user
}
}
}
// Добавьте методы для выхода пользователя, регистрации и других операций, если нужно // Добавьте методы для выхода пользователя, регистрации и других операций, если нужно
} }

View File

@ -0,0 +1,104 @@
package com.example.pmuapp.models.user.model.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.pmuapp.models.user.Dao.PetDao
import com.example.pmuapp.models.user.model.Pet
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class PetViewModel(private val petDao: PetDao) : ViewModel() {
private val _pet = MutableStateFlow<Pet?>(null)
val pet: StateFlow<Pet?> get() = _pet
private val _pets = MutableStateFlow<List<Pet>>(emptyList())
val pets: StateFlow<List<Pet>> get()= _pets
// Метод для обновления списка питомцев
// Метод для обновления списка питомцев
fun updatePets(newPets: List<Pet>) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
// Save the new list of pets to the database
petDao.insertAll(newPets)
// Retrieve the updated list of pets as a Flow
val updatedPetsFlow = petDao.getAllPets()
// Collect the values from the Flow and update _pets
updatedPetsFlow.collect { updatedPets ->
// Convert java.util.List to kotlin.collections.List if needed
_pets.value = updatedPets.toList()
}
}
}
}
fun updatePet(updatedPet: Pet) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
// Update the specific pet in the database
petDao.updatePet(updatedPet)
}
}
viewModelScope.launch {
withContext(Dispatchers.IO) {
// Retrieve the updated list of pets as a Flow
val updatedPetsFlow = petDao.getAllPets()
// Collect the values from the Flow and update _pets
updatedPetsFlow.collect { updatedPets ->
// Convert java.util.List to kotlin.collections.List if needed
_pets.value = updatedPets.toList()
}
}
}
}
// Добавьте метод для создания питомца
fun createPet(pet: Pet) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
// Вставляем новую задачу в базу данных
petDao.insertPet(pet)
// Получаем актуальный список задач после вставки
val updatedPetsFlow = petDao.getAllPets()
Log.e("TAG", "222222222222222222222222")
// Collect the values from the Flow and update _pets
updatedPetsFlow.collect { updatedPets ->
// Convert java.util.List to kotlin.collections.List if needed
_pets.value = updatedPets.toList()
}
}
}
}
fun deletePet(pet: Pet) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
petDao.deletePet(pet)
}
}
}
fun getPet(Id: Int): StateFlow<Pet?> {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val task = petDao.getOne(Id)
_pet.value = task
}
}
return _pet
}
fun getPetsByUser(userId: Int) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
_pets.value = petDao.getByUid(userId)
}
}
}
}

View File

@ -1,9 +1,12 @@
package com.example.pmuapp.models.user.model.viewmodel package com.example.pmuapp.models.user.model.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.example.pmuapp.models.user.Dao.UserDao import com.example.pmuapp.models.user.Dao.UserDao
import com.example.pmuapp.models.user.model.Pet
import com.example.pmuapp.models.user.model.User import com.example.pmuapp.models.user.model.User
import com.example.pmuapp.models.user.model.UserWithPets
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
@ -11,9 +14,12 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
class UserViewModel(private val userDao: UserDao) : ViewModel() { class UserViewModel(private val userDao: UserDao) : ViewModel() {
private val _user = MutableStateFlow<User?>(null)
val user: StateFlow<User?> get() = _user
private val _users = MutableStateFlow<List<User>>(emptyList()) private val _users = MutableStateFlow<List<User>>(emptyList())
val users: StateFlow<List<User>> get() = _users val users: StateFlow<List<User>> get() = _users
// Метод для обновления списка пользователей // Метод для обновления списка пользователей
fun updateUsers(newUsers: List<User>) { fun updateUsers(newUsers: List<User>) {
viewModelScope.launch { viewModelScope.launch {
@ -22,6 +28,17 @@ class UserViewModel(private val userDao: UserDao) : ViewModel() {
} }
} }
} }
fun updateUsers() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val updatedUsersFlow = userDao.getUsersWithPets()
updatedUsersFlow.collect { updatedUsers ->
_users.value = updatedUsers.toList()
}
}
}
}
// Метод для входа пользователя // Метод для входа пользователя
fun loginUser(login: String, password: String) { fun loginUser(login: String, password: String) {
@ -33,4 +50,37 @@ class UserViewModel(private val userDao: UserDao) : ViewModel() {
} }
} }
} }
fun updateUser(updatedUser: User) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
Log.e("TAG", "111111111111111111111")
// Update the specific pet in the database
userDao.update(updatedUser)
// Retrieve the updated list of pets as a Flow
val updatedUsersFlow = userDao.getUsersWithPets()
Log.e("TAG", "222222222222222222222222")
// Collect the values from the Flow and update _pets
updatedUsersFlow.collect { updatedUsers ->
// Convert java.util.List to kotlin.collections.List if needed
_users.value = updatedUsers.toList()
}
Log.e("TAG", "333333333333333333333333")
}
}
}
fun getUser(userId: Int): StateFlow<User?> {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val user = userDao.getUserById(userId)
_user.value = user
}
}
return _user
}
} }