Лаб 3 изменение действий под новые модели. Начало

This commit is contained in:
Kate 2023-11-13 19:42:47 +04:00
parent e12cc347c3
commit 17754f6e72
19 changed files with 165 additions and 115 deletions

Binary file not shown.

View File

@ -9,36 +9,26 @@
<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/Dao/PetDao.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/PetImageDao.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/Dao/UserDao.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/database/AppDatabase.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/PetImage.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/PetWithImage.kt" 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/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/executionHistory/executionHistory.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.bin" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.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/8.0/fileHashes/resourceHashesCache.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/resourceHashesCache.bin" 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" />
<change beforePath="$PROJECT_DIR$/.gradle/file-system.probe" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/file-system.probe" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/kotlinc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/kotlinc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.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/MainComposeActivity.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/MainComposeActivity.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/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/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/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/res/drawable/JNuFnEwXb10.jpg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/res/drawable/skNIwe8OnDc.jpg" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/res/drawable/Лекция 6.pdf" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/build.gradle.kts" beforeDir="false" afterPath="$PROJECT_DIR$/build.gradle.kts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/gradle.properties" beforeDir="false" afterPath="$PROJECT_DIR$/gradle.properties" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -94,8 +84,8 @@
<list>
<option value="Kotlin File" />
<option value="Interface" />
<option value="Kotlin Class" />
<option value="Kotlin Interface" />
<option value="Kotlin Class" />
</list>
</option>
</component>
@ -121,22 +111,22 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ASKED_ADD_EXTERNAL_FILES": "true",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.cidr.known.project.marker": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"cidr.known.project.marker": "true",
"com.android.tools.idea.devicemanager.tab": "Physical",
"last_opened_file_path": "C:/Users/Kate/AndroidStudioProjects/lab4compose",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.17",
"project.structure.side.proportion": "0.2",
"settings.editor.selected.configurable": "project.kotlinCompiler"
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&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;cidr.known.project.marker&quot;: &quot;true&quot;,
&quot;com.android.tools.idea.devicemanager.tab&quot;: &quot;Physical&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;,
&quot;project.structure.side.proportion&quot;: &quot;0.2&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;project.kotlinCompiler&quot;
}
}]]></component>
}</component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\models\user\viewmodels" />
@ -152,6 +142,7 @@
<recent name="com.example.pmuapp.composeui" />
</key>
<key name="MoveKotlinTopLevelDeclarationsDialog.RECENTS_KEY">
<recent name="com.example.pmuapp.models.user.model.viewmodel" />
<recent name="com.example.pmuapp.composeui" />
</key>
<key name="CopyKotlinDeclarationDialog.RECENTS_KEY">
@ -306,7 +297,14 @@
<option name="project" value="LOCAL" />
<updated>1698258953508</updated>
</task>
<option name="localTasksCounter" value="11" />
<task id="LOCAL-00011" summary="Лаб 3 создание моделей">
<created>1699816471908</created>
<option name="number" value="00011" />
<option name="presentableId" value="LOCAL-00011" />
<option name="project" value="LOCAL" />
<updated>1699816471908</updated>
</task>
<option name="localTasksCounter" value="12" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -342,6 +340,7 @@
<MESSAGE value="Лаб 2 выглядит как предварительный конец 2 лабы" />
<MESSAGE value="Лаб 2 вроде конец" />
<MESSAGE value="Лаб 3 начало" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 3 начало" />
<MESSAGE value="Лаб 3 создание моделей" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 3 создание моделей" />
</component>
</project>

View File

@ -65,7 +65,10 @@ dependencies {
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2")
implementation ("io.coil-kt:coil-compose:1.4.0")
// Room

View File

@ -1,6 +1,5 @@
package com.example.pmuapp.composeui
import android.os.Build
import android.os.Build.*
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Image
@ -25,19 +24,18 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
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.AuthViewModel
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
@RequiresApi(VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditPet(navController: NavController ,authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) {
fun EditPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) {
val pet = (authViewModel.currentUser?.petId ?: emptyList()).find { it.id == petId }
var petName by remember { mutableStateOf(pet?.name ?: "") }

View File

@ -14,7 +14,7 @@ import androidx.compose.ui.unit.dp
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.AuthViewModel
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel

View File

@ -1,11 +1,5 @@
package com.example.pmuapp.composeui
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.widget.TextView
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@ -15,42 +9,32 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.example.pmuapp.R
import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.AuthViewModel
import com.example.pmuapp.models.user.model.User
import com.example.pmuapp.ui.theme.PMUappTheme
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Login(
navController: NavHostController,
authViewModel: AuthViewModel,
users: List<User>
navController: NavController,
authViewModel: AuthViewModel
) {
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val users by authViewModel.currentUser.collectAsState()
Column(
modifier = Modifier
@ -82,11 +66,12 @@ fun Login(
Button(
onClick = {
val authenticatedUser = users.find { it.login == username && it.password == password }
val authenticatedUser = authViewModel.loginUser(username, password)
if (authenticatedUser != null) {
authViewModel.currentUser = authenticatedUser
// Аутентификация успешна
navController.navigate(Screen.Profile.route)
} else {
// Аутентификация не удалась
println("Authentication failed")
}
},
@ -95,10 +80,10 @@ fun Login(
Text("Login")
}
// Вы можете также использовать users для дополнительных проверок или вывода информации
users?.let {
Text("Current User: ${it.name}")
}
}
}

View File

@ -5,7 +5,6 @@ import androidx.annotation.RequiresApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@ -25,14 +24,14 @@ 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.AuthViewModel
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
@RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlayPet(navController: NavController,authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) {
fun PlayPet(navController: NavController, authViewModel: AuthViewModel, petViewModel: PetViewModel, userViewModel: UserViewModel, petId: Int) {
val pet = (authViewModel.currentUser?.petId ?: emptyList()).find { it.id == petId }
Column(

View File

@ -49,7 +49,7 @@ fun Profile(navController: NavController,currentUser: User?, onSaveClick: (User)
) {
currentUser?.let { user ->
Image(
painter = rememberImagePainter(data = user.imageResId),
painter = rememberImagePainter(data = user.imageUri),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
@ -108,8 +108,8 @@ fun Profile(navController: NavController,currentUser: User?, onSaveClick: (User)
nameState.value,
loginState.value,
passwordState.value,
currentUser?.petId ?: emptyList(),
selectedImageUri.value?.toString() ?: "",
currentUser?.pets ?: emptyList(),
selectedImageUri.value?.toString() ?: ""
)
onSaveClick(updatedUser)
},
@ -117,6 +117,8 @@ fun Profile(navController: NavController,currentUser: User?, onSaveClick: (User)
) {
Text("Сохранить")
}
Button(
onClick = {
navController.navigate(Screen.Login.route)

View File

@ -1,7 +1,6 @@
package com.example.pmuapp.composeui.navigation
import CreatePet
import android.content.res.Configuration
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Box
@ -17,7 +16,6 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
@ -27,7 +25,6 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
@ -46,10 +43,9 @@ import com.example.pmuapp.composeui.PlayPet
import com.example.pmuapp.composeui.Profile
import com.example.pmuapp.models.user.composeui.PetList
import com.example.pmuapp.models.user.composeui.UserList
import com.example.pmuapp.models.user.model.AuthViewModel
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel
import com.example.pmuapp.models.user.model.UserViewModel
import com.example.pmuapp.ui.theme.PMUappTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@ -123,11 +119,11 @@ fun Navbar(
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun NavHost(
navController: NavHostController,
innerPadding: PaddingValues,
authViewModel: AuthViewModel,
userViewModel: UserViewModel,
petViewModel: PetViewModel
navController: NavHostController,
innerPadding: PaddingValues,
authViewModel: AuthViewModel,
userViewModel: UserViewModel,
petViewModel: PetViewModel
) {
NavHost(
navController = navController,

View File

@ -6,7 +6,6 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
@ -17,8 +16,6 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
@ -28,9 +25,8 @@ 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.AuthViewModel
import com.example.pmuapp.models.user.model.viewmodel.AuthViewModel
import com.example.pmuapp.models.user.model.PetViewModel
import com.example.pmuapp.models.user.model.User
import com.example.pmuapp.models.user.model.UserViewModel
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)

View File

@ -1,10 +0,0 @@
package com.example.pmuapp.models.user.model
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
class AuthViewModel : ViewModel() {
var currentUser: User? by mutableStateOf(null)
}

View File

@ -10,22 +10,23 @@ import androidx.room.Relation
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true)
val id: Int,
val id: Int = 0,
val name: String,
val login: String,
val password: String,
@Relation(
entity = Pet::class,
parentColumn = "id",
entityColumn = "user_id"
)
val pets: List<Pet>,
@ColumnInfo(name = "image_res_id")
val imageResId: String
@Relation(parentColumn = "id", entityColumn = "user_id")
var pets: List<Pet> = emptyList(),
val imageUri: String = ""
) {
@Ignore
constructor(id: Int, name: String, login: String, password: String, imageResId: Int) :
this(id, name, login, password, emptyList(), imageResId)
constructor(
name: String,
login: String,
password: String,
pets: List<Pet>,
imageUri: String
) : this(0, name, login, password, pets, imageUri)
fun addPet(pet: Pet): User {
val updatedPets = pets.toMutableList()
updatedPets.add(pet)

View File

@ -0,0 +1,45 @@
package com.example.pmuapp.models.user.model.viewmodel
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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
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()
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 после успешной аутентификации
_currentUser.value = user
}
}
}
// Добавьте методы для выхода пользователя, регистрации и других операций, если нужно
}

View File

@ -0,0 +1,36 @@
package com.example.pmuapp.models.user.model.viewmodel
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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class UserViewModel(private val userDao: UserDao) : ViewModel() {
private val _users = MutableStateFlow<List<User>>(emptyList())
val users: StateFlow<List<User>> get() = _users
// Метод для обновления списка пользователей
fun updateUsers(newUsers: List<User>) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
_users.value = newUsers
}
}
}
// Метод для входа пользователя
fun loginUser(login: String, password: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
val user = userDao.getUserByLoginAndPassword(login, password)
// Здесь должно быть обновление списка пользователей, но не _currentUser
// Также, вам, возможно, нужно вызвать метод updateUsers с обновленным списком пользователей
}
}
}
}