diff --git a/.gradle/8.0/checksums/checksums.lock b/.gradle/8.0/checksums/checksums.lock
deleted file mode 100644
index fb0feb4..0000000
Binary files a/.gradle/8.0/checksums/checksums.lock and /dev/null differ
diff --git a/.gradle/8.0/checksums/md5-checksums.bin b/.gradle/8.0/checksums/md5-checksums.bin
deleted file mode 100644
index 854ce88..0000000
Binary files a/.gradle/8.0/checksums/md5-checksums.bin and /dev/null differ
diff --git a/.gradle/8.0/checksums/sha1-checksums.bin b/.gradle/8.0/checksums/sha1-checksums.bin
deleted file mode 100644
index 7117ade..0000000
Binary files a/.gradle/8.0/checksums/sha1-checksums.bin and /dev/null differ
diff --git a/.gradle/8.0/dependencies-accessors/dependencies-accessors.lock b/.gradle/8.0/dependencies-accessors/dependencies-accessors.lock
deleted file mode 100644
index e232e16..0000000
Binary files a/.gradle/8.0/dependencies-accessors/dependencies-accessors.lock and /dev/null differ
diff --git a/.gradle/8.0/dependencies-accessors/gc.properties b/.gradle/8.0/dependencies-accessors/gc.properties
deleted file mode 100644
index e69de29..0000000
diff --git a/.gradle/8.0/executionHistory/executionHistory.bin b/.gradle/8.0/executionHistory/executionHistory.bin
deleted file mode 100644
index 1577863..0000000
Binary files a/.gradle/8.0/executionHistory/executionHistory.bin and /dev/null differ
diff --git a/.gradle/8.0/executionHistory/executionHistory.lock b/.gradle/8.0/executionHistory/executionHistory.lock
deleted file mode 100644
index ceba8be..0000000
Binary files a/.gradle/8.0/executionHistory/executionHistory.lock and /dev/null differ
diff --git a/.gradle/8.0/fileChanges/last-build.bin b/.gradle/8.0/fileChanges/last-build.bin
deleted file mode 100644
index f76dd23..0000000
Binary files a/.gradle/8.0/fileChanges/last-build.bin and /dev/null differ
diff --git a/.gradle/8.0/fileHashes/fileHashes.bin b/.gradle/8.0/fileHashes/fileHashes.bin
deleted file mode 100644
index 6fcc407..0000000
Binary files a/.gradle/8.0/fileHashes/fileHashes.bin and /dev/null differ
diff --git a/.gradle/8.0/fileHashes/fileHashes.lock b/.gradle/8.0/fileHashes/fileHashes.lock
deleted file mode 100644
index 6b6ca6b..0000000
Binary files a/.gradle/8.0/fileHashes/fileHashes.lock and /dev/null differ
diff --git a/.gradle/8.0/fileHashes/resourceHashesCache.bin b/.gradle/8.0/fileHashes/resourceHashesCache.bin
deleted file mode 100644
index cb82d5d..0000000
Binary files a/.gradle/8.0/fileHashes/resourceHashesCache.bin and /dev/null differ
diff --git a/.gradle/8.0/gc.properties b/.gradle/8.0/gc.properties
deleted file mode 100644
index e69de29..0000000
diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock
deleted file mode 100644
index ffe221f..0000000
Binary files a/.gradle/buildOutputCleanup/buildOutputCleanup.lock and /dev/null differ
diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties
deleted file mode 100644
index 4e9d3df..0000000
--- a/.gradle/buildOutputCleanup/cache.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-#Sun Oct 08 15:55:30 GMT+04:00 2023
-gradle.version=8.0
diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin
deleted file mode 100644
index 459d3ed..0000000
Binary files a/.gradle/buildOutputCleanup/outputFiles.bin and /dev/null differ
diff --git a/.gradle/file-system.probe b/.gradle/file-system.probe
deleted file mode 100644
index f552e8a..0000000
Binary files a/.gradle/file-system.probe and /dev/null differ
diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties
deleted file mode 100644
index e69de29..0000000
diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml
index 51f6d40..c56b956 100644
--- a/.idea/kotlinc.xml
+++ b/.idea/kotlinc.xml
@@ -1,7 +1,7 @@
-
+
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 111fe90..e11a5b2 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -9,33 +9,55 @@
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
-
+
@@ -49,30 +71,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
@@ -118,8 +117,11 @@
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.cidr.known.project.marker": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
+ "android-custom-viewC:/Users/Kate/AppData/Local/Android/Sdk/sources/android-31/android/view/View.java_SELECTED": "View",
+ "android-custom-viewC:/Users/Kate/AppData/Local/Android/Sdk/sources/android-31/android/view/ViewGroup.java_SELECTED": "ViewGroup",
"cidr.known.project.marker": "true",
"com.android.tools.idea.devicemanager.tab": "Physical",
+ "com.google.services.firebase.aqiPopupShown": "true",
"last_opened_file_path": "C:/Users/Kate/AndroidStudioProjects/Ihonkina_PIbd-31_PMU",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.17",
@@ -304,7 +306,14 @@
1699816471908
-
+
+ 1699890169920
+
+
+
+ 1699890169920
+
+
@@ -341,6 +350,41 @@
-
+
+
+
+
+
+
+
+ file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt
+ 31
+
+
+
+
+
+
+ file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt
+ 27
+
+
+
+ file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt
+ 28
+
+
+
+ file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt
+ 108
+
+
+
+ file://$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt
+ 217
+
+
+
+
\ No newline at end of file
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 43568d4..09a9561 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -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")
+
+
+
}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt b/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt
index 49d07db..db83226 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt
@@ -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()
diff --git a/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt b/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt
index 5f16aa8..d423a3c 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt
@@ -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)
) {
diff --git a/app/src/main/java/com/example/pmuapp/composeui/Home.kt b/app/src/main/java/com/example/pmuapp/composeui/Home.kt
index 6c798cd..1433088 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/Home.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/Home.kt
@@ -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)
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/composeui/Login.kt b/app/src/main/java/com/example/pmuapp/composeui/Login.kt
index 7b4922f..f0def4d 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/Login.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/Login.kt
@@ -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}")
- }
}
}
diff --git a/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt b/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt
index f29a8f9..8fb5b8e 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt
@@ -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),
diff --git a/app/src/main/java/com/example/pmuapp/composeui/Profile.kt b/app/src/main/java/com/example/pmuapp/composeui/Profile.kt
index ccc67d6..fa8dabc 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/Profile.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/Profile.kt
@@ -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)
diff --git a/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt b/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt
index 6cc181e..a886fd6 100644
--- a/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt
+++ b/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt
@@ -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) }
diff --git a/app/src/main/java/com/example/pmuapp/models/user/Dao/PetDao.kt b/app/src/main/java/com/example/pmuapp/models/user/Dao/PetDao.kt
index a190a8f..9a29eee 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/Dao/PetDao.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/Dao/PetDao.kt
@@ -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>
-
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun insertAll(pets: kotlin.collections.List)
@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
+ @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
}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt b/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt
index 3ceb406..4808ba1 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt
@@ -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>
-}
\ No newline at end of file
+//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>
+//}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt b/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt
index f68d25e..f85e3d4 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt
@@ -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
+ @Transaction
+ @Query("SELECT * FROM users")
+ fun getUsersWithPets(): Flow>
@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?
+
+
}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt b/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt
index 1e12479..dc98333 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt
@@ -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 = "Удалить"
+ )
}
}
}
}
}
+
}
}
diff --git a/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt b/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt
index ccf85ac..e076e80 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt
@@ -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}")
+ }
}
}
}
diff --git a/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt b/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt
index 27085a2..2bdea4c 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt
@@ -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)
}
}
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt b/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt
index 111aa21..82fab2a 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt
@@ -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
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt b/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt
index cab88fa..63ddfd8 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt
@@ -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
- }
-}
\ No newline at end of file
+//
+//@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
+// }
+//}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt b/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt
index 6252508..769feb9 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt
@@ -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?
+//)
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/User.kt b/app/src/main/java/com/example/pmuapp/models/user/model/User.kt
index bbc9ffd..bc3c40b 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/model/User.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/User.kt
@@ -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 = emptyList(),
+ val name: String = "",
+ val login: String = "",
+ val password: String = "",
val imageUri: String = ""
-) {
+)
+ {
@Ignore
constructor(
name: String,
login: String,
password: String,
- pets: List,
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
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/UserWithPets.kt b/app/src/main/java/com/example/pmuapp/models/user/model/UserWithPets.kt
new file mode 100644
index 0000000..b4b68a6
--- /dev/null
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/UserWithPets.kt
@@ -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
+)
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt b/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt
index a48c066..c8c1538 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/AuthViewModel.kt
@@ -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(null)
- val currentUser: StateFlow get() = _currentUser.asStateFlow()
+ val currentUser: StateFlow 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
+
+ }
+ }
+ }
+
// Добавьте методы для выхода пользователя, регистрации и других операций, если нужно
}
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/PetViewModel.kt b/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/PetViewModel.kt
new file mode 100644
index 0000000..b78378b
--- /dev/null
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/PetViewModel.kt
@@ -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(null)
+ val pet: StateFlow get() = _pet
+ private val _pets = MutableStateFlow>(emptyList())
+ val pets: StateFlow> get()= _pets
+
+ // Метод для обновления списка питомцев
+ // Метод для обновления списка питомцев
+ fun updatePets(newPets: List) {
+ 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 {
+ 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)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt b/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt
index 883042c..b0818ed 100644
--- a/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt
+++ b/app/src/main/java/com/example/pmuapp/models/user/model/viewmodel/UserViewModel.kt
@@ -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(null)
+ val user: StateFlow get() = _user
private val _users = MutableStateFlow>(emptyList())
val users: StateFlow> get() = _users
+
// Метод для обновления списка пользователей
fun updateUsers(newUsers: List) {
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 {
+ viewModelScope.launch {
+ withContext(Dispatchers.IO) {
+ val user = userDao.getUserById(userId)
+ _user.value = user
+ }
+ }
+ return _user
+ }
+
+ }