Лаб 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"?>
<project version="4">
<component name="Kotlin2JvmCompilerArguments">
<option name="jvmTarget" value="11" />
<option name="jvmTarget" value="17" />
</component>
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.8.20" />

View File

@ -9,33 +9,55 @@
<option name="autoReloadType" value="NONE" />
</component>
<component name="ChangeListManager">
<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/viewmodel/UserViewModel.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/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/sha1-checksums.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/checksums/sha1-checksums.bin" afterDir="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/buildOutputCleanup/buildOutputCleanup.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" afterDir="false" />
<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/UserWithPets.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" />
<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" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/dependencies-accessors/dependencies-accessors.lock" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/dependencies-accessors/gc.properties" beforeDir="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$/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/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/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/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/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/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>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</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">
<projectState path="$PROJECT_DIR$">
<ProjectState />
@ -49,30 +71,7 @@
</task>
<projects_view>
<tree_state>
<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>
<expand />
<select />
</tree_state>
</projects_view>
@ -118,8 +117,11 @@
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.cidr.known.project.marker&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;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;project.structure.last.edited&quot;: &quot;Modules&quot;,
&quot;project.structure.proportion&quot;: &quot;0.17&quot;,
@ -304,7 +306,14 @@
<option name="project" value="LOCAL" />
<updated>1699816471908</updated>
</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 />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -341,6 +350,41 @@
<MESSAGE value="Лаб 2 вроде конец" />
<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>
</project>

View File

@ -31,11 +31,11 @@ android {
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "11"
jvmTarget = "17"
}
buildFeatures {
compose = true
@ -87,4 +87,9 @@ dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
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.navigation.NavController
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.User
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
@OptIn(ExperimentalMaterial3Api::class)
@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 petName by remember { mutableStateOf("") }
@ -70,12 +71,13 @@ fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) {
Button(
onClick = {
if (petName.isNotEmpty()) {
val newPet = Pet(0, petName, selectedImage, "")
val newPet = Pet(petName, selectedImage, "", authViewModel.currentUser.value )
onSaveClick(newPet)
petName = ""
selectedImage = R.drawable.pet1
navController.popBackStack()
navController.navigate(Screen.Home.route)
}
},
modifier = Modifier.fillMaxWidth()

View File

@ -28,18 +28,18 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
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.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@RequiresApi(VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) {
val pet = (authViewModel.currentUser?.petId ?: emptyList()).find { it.id == petId }
fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, pet : Pet?, onSaveClick: (Pet) -> Unit) {
var petName by remember { mutableStateOf(pet?.name ?: "") }
var petNotes by remember { mutableStateOf(pet?.notes ?: "") }
var petName = remember { mutableStateOf(pet?.name ?: "") }
var petNotes = remember { mutableStateOf(pet?.notes ?: "") }
Column(
modifier = Modifier
@ -47,18 +47,20 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
.padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
val imageResId = pet?.imageResId ?: 0
Image(
painter = painterResource(id = imageResId),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
if(pet!=null) {
val imageResId = pet?.imageResId ?: 0
Image(
painter = painterResource(id = imageResId),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
}
OutlinedTextField(
value = petName,
onValueChange = { petName = it },
value = petName.value,
onValueChange = { petName.value = it },
label = { Text("Имя питомца") },
modifier = Modifier
.fillMaxWidth()
@ -72,8 +74,8 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
)
TextField(
value = petNotes,
onValueChange = { petNotes = it },
value = petNotes.value,
onValueChange = { petNotes.value = it },
label = { Text("Заметки") },
modifier = Modifier
.fillMaxWidth()
@ -86,17 +88,26 @@ fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewM
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(
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)
) {

View File

@ -1,11 +1,13 @@
package com.example.pmuapp.composeui
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
@ -15,11 +17,12 @@ import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.composeui.PetList
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("RememberReturnType")
@Composable
fun Home(navController: NavController, authViewModel: AuthViewModel, petViewModel:PetViewModel, userViewModel:UserViewModel) {
fun Home(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
@ -34,7 +37,7 @@ fun Home(navController: NavController, authViewModel: AuthViewModel, petViewMode
}
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.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@ -21,9 +22,12 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@ -34,7 +38,6 @@ fun Login(
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val users by authViewModel.currentUser.collectAsState()
Column(
modifier = Modifier
@ -66,24 +69,25 @@ fun Login(
Button(
onClick = {
val authenticatedUser = authViewModel.loginUser(username, password)
if (authenticatedUser != null) {
// Аутентификация успешна
navController.navigate(Screen.Profile.route)
} else {
// Аутентификация не удалась
println("Authentication failed")
authViewModel.viewModelScope.launch {
authViewModel.loginUser(username, password)
}
// Добавляем небольшую задержку (например, 100 мс) для обеспечения завершения операции входа в систему
// delay(1000)
val authenticatedUser = authViewModel.currentUser.value
if (authenticatedUser != null) {
navController.navigate(Screen.Home.route)
} else {
println("Аутентификация не удалась")
}
},
modifier = Modifier.fillMaxWidth()
) {
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.navigation.NavController
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.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
@RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) {
val pet = (authViewModel.currentUser?.petId ?: emptyList()).find { it.id == petId }
fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, pet: Pet?) {
Column(
modifier = Modifier
@ -40,15 +40,16 @@ fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewM
.padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
val imageResId = pet?.imageResId ?: 0
Image(
painter = painterResource(id = imageResId),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
if (pet!=null) {
val imageResId = pet?.imageResId ?: 0
Image(
painter = painterResource(id = imageResId),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
)
}
Text(
text = pet?.name ?: "",
style = TextStyle(fontWeight = FontWeight.Bold, fontSize = 24.sp),

View File

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

View File

@ -1,6 +1,7 @@
package com.example.pmuapp.composeui.navigation
import CreatePet
import android.annotation.SuppressLint
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Box
@ -24,7 +25,9 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
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.PlayPet
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.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.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
import com.example.pmuapp.models.user.model.viewmodel.PetViewModel
import com.example.pmuapp.models.user.model.viewmodel.UserViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@ -116,6 +125,7 @@ fun Navbar(
}
}
@SuppressLint("StateFlowValueCalledInComposition", "SuspiciousIndentation")
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun NavHost(
@ -131,17 +141,18 @@ fun NavHost(
modifier = Modifier.padding(innerPadding)
) {
composable(Screen.Login.route) {
Login(navController, authViewModel,userViewModel.getUsers())
Login(navController, authViewModel)
}
composable(Screen.Profile.route) {
val currentUser = authViewModel.currentUser ?: userViewModel.getUsers().firstOrNull()
val currentUser = authViewModel.currentUser.value
if (currentUser != null) {
Profile(navController,
currentUser = currentUser,
currentUser = currentUser ,
onSaveClick = {updatedUser ->
userViewModel.updateUser(updatedUser)
authViewModel.currentUser = updatedUser
navController.navigate(Screen.Profile.route)
// authViewModel.updateCurrentUset(currentUser?.id ?:-1)
navController.navigate(Screen.UserList.route)
}
)
} else {
@ -149,18 +160,30 @@ fun NavHost(
}
composable(Screen.UserList.route) { UserList(navController, userViewModel) }
composable(Screen.Home.route) { Home(navController, authViewModel,petViewModel,userViewModel) }
composable(Screen.CreatePet.route) {
val currentUser = authViewModel.currentUser ?: userViewModel.getUsers().firstOrNull()
CreatePet ( navController, onSaveClick = { newPet ->
var adedPet = petViewModel.createPet(newPet)
userViewModel.addPetToUser(currentUser?.id ?:0, adedPet)
authViewModel.currentUser = userViewModel.getUser(currentUser?.id ?:0)
}
composable(Screen.Home.route){
val currentUser = authViewModel.currentUser
if (currentUser != null) {
Home(navController,
authViewModel,
petViewModel,
userViewModel
)
} else {
}
}
composable(Screen.CreatePet.route) {
val currentUser = authViewModel.currentUser
val id: Int = currentUser.value?.id?.toInt() ?: 0
CreatePet ( navController, authViewModel , onSaveClick = { newPet ->
petViewModel.createPet(newPet)
//userViewModel.addTask(currentUser?.id ?:0, adedTask)
// authViewModel.updateCurrentUset(id)
}
)
}
composable(
Screen.UserView.route,
arguments = listOf(navArgument("id") { type = NavType.IntType })
@ -171,7 +194,7 @@ fun NavHost(
contentAlignment = Alignment.TopCenter,
modifier = Modifier.fillMaxSize()
) {
PetList(navController,authViewModel, petViewModel, userViewModel, userId)
PetList(navController,authViewModel, petViewModel, userViewModel, userId+1)
}
}
composable(
@ -179,16 +202,23 @@ fun NavHost(
arguments = listOf(navArgument("id") { type = NavType.IntType })
) { backStackEntry ->
val petId = backStackEntry.arguments?.getInt("id") ?: -1
PlayPet(navController,authViewModel, petViewModel, userViewModel, petId)
val pet = petViewModel.getPet(petId)
PlayPet(navController,authViewModel, petViewModel, userViewModel, pet.value)
}
composable(
Screen.EditPet.route,
arguments = listOf(navArgument("id") { type = NavType.IntType })
) { backStackEntry ->
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
fun MainNavbar() {
val navController = rememberNavController()
val authViewModel = remember { AuthViewModel() }
val userViewModel =remember {UserViewModel() }
val petViewModel = remember {PetViewModel()}
val context = LocalContext.current
val database: AppDatabase = AppDatabase.getInstance(context)
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 currentDestination = navBackStackEntry?.destination
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.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy
import androidx.room.Query;
import androidx.room.Transaction
import androidx.room.Update;
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 java.util.List;
@ -20,7 +19,8 @@ import java.util.List;
interface PetDao {
@Query("SELECT * FROM pets")
fun getAllPets(): Flow<List<Pet>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(pets: kotlin.collections.List<Pet>)
@Insert
suspend fun insertPet(pet: Pet)
@ -29,8 +29,8 @@ interface PetDao {
@Delete
suspend fun deletePet(pet: Pet)
@Transaction
@Query("SELECT * FROM pets WHERE id = :petId")
fun getPetWithImageById(petId: Int): Flow<PetWithImage?>
@Query("select * from pets where pets.id = :uid ")
suspend fun getOne(uid: Int):Pet
@Query("select * from pets where pets.user_id = :uid")
suspend fun getByUid(uid: Int): kotlin.collections.List<Pet>
}

View File

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

View File

@ -5,17 +5,22 @@ import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction
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.UserWithPets
import kotlinx.coroutines.flow.Flow
import java.util.List;
@Dao
interface UserDao {
@Query("select * from users")
suspend fun getAll(): List<User>
@Transaction
@Query("SELECT * FROM users")
fun getUsersWithPets(): Flow<List<User>>
@Insert
suspend fun insert(user: User)
@ -26,9 +31,20 @@ interface UserDao {
@Delete
suspend fun delete(user: User)
@Query("SELECT * FROM users WHERE login = :login AND password = :password")
suspend fun getUserByLoginAndPassword(login: String, password: String): User?
// @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): 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?
}

View File

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

View File

@ -1,5 +1,6 @@
package com.example.pmuapp.models.user.composeui
import android.annotation.SuppressLint
import android.content.res.Configuration
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
@ -9,31 +10,35 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.pmuapp.composeui.navigation.Screen
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
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun UserList(navController: NavController?, userViewModel: UserViewModel) {
userViewModel.updateUsers()
var users = userViewModel.users.value
fun UserList(navController: NavController?,
userViewModel: UserViewModel
) {
val users = userViewModel.users.value
Column(Modifier.padding(all = 10.dp)) {
users.forEachIndexed() { index, user ->
val userId = Screen.UserView.route.replace("{id}", index.toString())
Button(
modifier = Modifier
.fillMaxWidth()
.padding(all = 10.dp),
onClick = { navController?.navigate(userId) }) {
Text("${user.login}")
if (users.count()!=0) {
Column(Modifier.padding(all = 10.dp)) {
users.forEachIndexed() { index, user ->
val userId = Screen.UserView.route.replace("{id}", index.toString())
Button(
modifier = Modifier
.fillMaxWidth()
.padding(all = 10.dp),
onClick = { navController?.navigate(userId) }) {
Text("${user.login}")
}
}
}
}

View File

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

View File

@ -1,33 +1,38 @@
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.Entity
import androidx.room.ForeignKey
import androidx.room.Ignore
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(
@PrimaryKey(autoGenerate = true)
val id: Int,
val name: String,
@ColumnInfo(name = "image_res_id")
val imageResId: Int,
@ColumnInfo(name = "user_id", index = true)
val userId: Int, // Changed from groupId to userId
val notes: String
) {
@Ignore
constructor(name: String, imageResId: Int, notes: String) :
this(0, name, imageResId, notes)
constructor(name: String, imageResId: Int, notes: String, user: User?,) :
this(0, name, imageResId, user?.id ?:0, notes)
@Relation(parentColumn = "id", entityColumn = "pet_id")
var petImage: PetImage? = null
// @Relation(parentColumn = "id", entityColumn = "pet_id")
// var petImage: PetImage? = null
override fun equals(other: Any?): Boolean {
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.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "pet_images")
data class PetImage(
@PrimaryKey(autoGenerate = true)
val id: Int,
@ColumnInfo(name = "pet_id")
val petId: Int,
val imageData: Int
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PetImage
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id ?: -1
}
}
//
//@Entity(tableName = "pet_images")
//data class PetImage(
// @PrimaryKey(autoGenerate = true)
// val id: Int,
// @ColumnInfo(name = "pet_id")
// val petId: Int,
// val imageData: Int
//) {
// override fun equals(other: Any?): Boolean {
// if (this === other) return true
// if (javaClass != other?.javaClass) return false
// other as PetImage
// if (id != other.id) return false
// return true
// }
//
// override fun hashCode(): Int {
// return id ?: -1
// }
//}

View File

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

View File

@ -6,32 +6,24 @@ import androidx.room.Ignore
import androidx.room.PrimaryKey
import androidx.room.Relation
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val name: String,
val login: String,
val password: String,
@Relation(parentColumn = "id", entityColumn = "user_id")
var pets: List<Pet> = emptyList(),
val name: String = "",
val login: String = "",
val password: String = "",
val imageUri: String = ""
) {
)
{
@Ignore
constructor(
name: String,
login: String,
password: String,
pets: List<Pet>,
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 {
if (this === other) return true
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
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.pmuapp.models.user.Dao.UserDao
import com.example.pmuapp.models.user.model.User
import com.example.pmuapp.models.user.model.UserWithPets
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class AuthViewModel(private val userDao: UserDao) : ViewModel() {
private val _currentUser = MutableStateFlow<User?>(null)
val currentUser: StateFlow<User?> get() = _currentUser.asStateFlow()
val currentUser: StateFlow<User?> get() = _currentUser
init {
/* init {
// Подписываемся на изменения в базе данных и обновляем _currentUser
viewModelScope.launch {
withContext(Dispatchers.IO) {
val users = userDao.getAll()
// Ваш код обработки данных, если необходимо
// Например, если вам нужно обновить _currentUser
_currentUser.value = users.firstOrNull()
}
}
}
// Метод для входа пользователя
fun loginUser(login: String, password: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val user = userDao.getUserByLoginAndPassword(login, password)
// Обновляем _currentUser после успешной аутентификации
val user = userDao.getUserByLoginAndPassword("", "")
_currentUser.value = user
}
}
}
*/
fun loginUser(username: String, password: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val user = userDao.getUserByLoginAndPassword(username, password)
_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
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
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.UserWithPets
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@ -11,9 +14,12 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
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())
val users: StateFlow<List<User>> get() = _users
// Метод для обновления списка пользователей
fun updateUsers(newUsers: List<User>) {
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) {
@ -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
}
}