Лаб 3 создание моделей

This commit is contained in:
Kate 2023-11-12 23:14:28 +04:00
parent 5b71cf1e4b
commit e12cc347c3
28 changed files with 356 additions and 195 deletions

Binary file not shown.

Binary file not shown.

View File

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

View File

@ -9,7 +9,16 @@
<option name="autoReloadType" value="NONE" />
</component>
<component name="ChangeListManager">
<list default="true" id="dc3793c7-c725-42e8-8eda-044c95f334c1" name="Changes" comment="Лаб 2 выглядит как предварительный конец 2 лабы">
<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" />
<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" />
@ -18,25 +27,25 @@
<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/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/composeui/PetList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/StudentView.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/StudentView.kt" afterDir="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/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/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" />
<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[RF8N601QWVE]" />
<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="ExternalProjectsData">
<projectState path="$PROJECT_DIR$">
<ProjectState />
@ -84,14 +93,16 @@
<option name="RECENT_TEMPLATES">
<list>
<option value="Kotlin File" />
<option value="Interface" />
<option value="Kotlin Class" />
<option value="Kotlin Interface" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_BRANCH_BY_REPOSITORY">
<map>
<entry key="$PROJECT_DIR$" value="Lab1" />
<entry key="$PROJECT_DIR$" value="Lab2" />
</map>
</option>
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
@ -100,7 +111,7 @@
<option name="stateVersion" value="1" />
</component>
<component name="ProblemsViewState">
<option name="selectedTabId" value="ProjectErrors" />
<option name="selectedTabId" value="CurrentFile" />
</component>
<component name="ProjectId" id="2WToW0mvjPzND9QiCAmC6MXKLwF" />
<component name="ProjectLevelVcsManager">
@ -119,17 +130,20 @@
"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/Ihonkina_PIbd-31_PMU/app/src/main/java/com/example/pmuapp/composeui/navigation",
"settings.editor.selected.configurable": "experimental"
"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>
<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" />
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\composeui\navigation" />
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\models\user\composeui" />
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\composeui" />
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\res\drawable" />
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp" />
</key>
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\composeui" />
@ -141,6 +155,7 @@
<recent name="com.example.pmuapp.composeui" />
</key>
<key name="CopyKotlinDeclarationDialog.RECENTS_KEY">
<recent name="com.example.pmuapp.models.user.Dao" />
<recent name="com.example.pmuapp.composeui.navigation" />
</key>
</component>
@ -270,7 +285,28 @@
<option name="project" value="LOCAL" />
<updated>1697086828529</updated>
</task>
<option name="localTasksCounter" value="8" />
<task id="LOCAL-00008" summary="Лаб 2 вроде конец">
<created>1698235676591</created>
<option name="number" value="00008" />
<option name="presentableId" value="LOCAL-00008" />
<option name="project" value="LOCAL" />
<updated>1698235676591</updated>
</task>
<task id="LOCAL-00009" summary="Лаб 3 начало">
<created>1698258901683</created>
<option name="number" value="00009" />
<option name="presentableId" value="LOCAL-00009" />
<option name="project" value="LOCAL" />
<updated>1698258901683</updated>
</task>
<task id="LOCAL-00010" summary="Лаб 3 начало">
<created>1698258953508</created>
<option name="number" value="00010" />
<option name="presentableId" value="LOCAL-00010" />
<option name="project" value="LOCAL" />
<updated>1698258953508</updated>
</task>
<option name="localTasksCounter" value="11" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -284,7 +320,7 @@
<entry key="branch">
<value>
<list>
<option value="Lab1" />
<option value="Lab3" />
</list>
</value>
</entry>
@ -304,6 +340,8 @@
<MESSAGE value="Лаб 2 нало работы с пользователем" />
<MESSAGE value="Лаб 2 питомцы просто добавлены" />
<MESSAGE value="Лаб 2 выглядит как предварительный конец 2 лабы" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 2 выглядит как предварительный конец 2 лабы" />
<MESSAGE value="Лаб 2 вроде конец" />
<MESSAGE value="Лаб 3 начало" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 3 начало" />
</component>
</project>

View File

@ -1,13 +1,13 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("com.google.devtools.ksp")
}
android {
namespace = "com.example.pmuapp"
compileSdk = 34
defaultConfig {
applicationId = "com.example.pmuapp"
minSdk = 24
@ -31,17 +31,17 @@ android {
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "1.8"
jvmTarget = "11"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.4.3"
kotlinCompilerExtensionVersion = "1.4.5"
}
packaging {
resources {
@ -50,10 +50,14 @@ android {
}
}
dependencies {
implementation ("io.coil-kt:coil-compose:1.4.0")
// Core
implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
// UI
implementation("androidx.activity:activity-compose:1.7.2")
implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.navigation:navigation-compose:2.6.0")
@ -61,9 +65,18 @@ dependencies {
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation("com.google.android.engage:engage-core:1.3.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("androidx.compose.ui:ui-graphics-android:1.5.3")
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2")
// Room
val room_version = "2.5.2"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
ksp("androidx.room:room-compiler:$room_version")
implementation("androidx.room:room-ktx:$room_version")
implementation("androidx.room:room-paging:$room_version")
// Tests
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")

View File

@ -1,9 +1,11 @@
package com.example.pmuapp
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
@ -14,6 +16,7 @@ import com.example.pmuapp.composeui.navigation.MainNavbar
import com.example.pmuapp.ui.theme.PMUappTheme
class MainComposeActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
@ -29,6 +32,7 @@ class MainComposeActivity : ComponentActivity() {
}
}
@RequiresApi(Build.VERSION_CODES.O)
@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable

View File

@ -0,0 +1,36 @@
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.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;
@Dao
interface PetDao {
@Query("SELECT * FROM pets")
fun getAllPets(): Flow<List<Pet>>
@Insert
suspend fun insertPet(pet: Pet)
@Update
suspend fun updatePet(pet: Pet)
@Delete
suspend fun deletePet(pet: Pet)
@Transaction
@Query("SELECT * FROM pets WHERE id = :petId")
fun getPetWithImageById(petId: Int): Flow<PetWithImage?>
}

View File

@ -0,0 +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>>
}

View File

@ -0,0 +1,34 @@
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.User;
import java.util.List;
@Dao
interface UserDao {
@Query("select * from users")
suspend fun getAll(): List<User>
@Insert
suspend fun insert(user: User)
@Update
suspend fun update(user: User)
@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 WHERE id = :userId")
suspend fun getUserWithPetsById(userId: Int): User?
}

View File

@ -0,0 +1,74 @@
package com.example.pmuapp.models.user.database
import android.content.Context
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
import kotlinx.coroutines.launch
@Database(entities = [User::class, Pet::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun petDao(): PetDao
abstract fun petImageDao(): PetImageDao
companion object {
private const val DB_NAME: String = "pmy-db"
@Volatile
private var INSTANCE: AppDatabase? = null
private suspend fun populateDatabase() {
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)
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)
}
}
fun getInstance(appContext: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
Room.databaseBuilder(
appContext,
AppDatabase::class.java,
DB_NAME
)
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
CoroutineScope(Dispatchers.IO).launch {
populateDatabase()
}
}
})
.build()
.also { INSTANCE = it }
}
}
}
}

View File

@ -4,65 +4,41 @@ 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")
data class Pet(
var id: Int,
@PrimaryKey(autoGenerate = true)
val id: Int,
val name: String,
@ColumnInfo(name = "image_res_id")
val imageResId: Int,
val notes: String
) : Serializable
) {
@Ignore
constructor(name: String, imageResId: Int, notes: String) :
this(0, name, imageResId, notes)
class PetViewModel : ViewModel() {
var pets: MutableState<List<Pet>> = mutableStateOf(
emptyList()
)
val availablePetImages: List<Int> = listOf(
R.drawable.pet1,
R.drawable.pet2,
R.drawable.pet3,
R.drawable.pet4,
R.drawable.pet5,
R.drawable.pet6,
R.drawable.pet7,
R.drawable.pet8,
)
@Relation(parentColumn = "id", entityColumn = "pet_id")
var petImage: PetImage? = null
fun createPet(newPet: Pet): Pet {
newPet.id = pets.value.size.toInt()
val updatedPets = pets.value.toMutableList()
updatedPets.add(newPet)
pets.value = updatedPets
return newPet
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Pet
if (id != other.id) return false
return true
}
fun deletePet(pet: Pet) {
val updatedPets = pets.value.toMutableList()
updatedPets.remove(pet)
pets.value = updatedPets
}
fun updatePet(updatedPet: Pet) {
val updatedPets = pets.value.toMutableList()
val index = updatedPets.indexOfFirst { it.id == updatedPet.id }
if (index != -1) {
updatedPets[index] = updatedPet
pets.value = updatedPets
}
override fun hashCode(): Int {
return id ?: -1
}
}
// fun updateUser(updatedUser: User) {
// val updatedUsers = users.value.toMutableList()
// val index = updatedUsers.indexOfFirst { it.login == updatedUser.login }
// if (index != -1) {
// updatedUsers[index] = updatedUser
// users.value = updatedUsers
// }
// }

View File

@ -0,0 +1,26 @@
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
}
}

View File

@ -0,0 +1,13 @@
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?
)

View File

@ -1,129 +1,47 @@
package com.example.pmuapp.models.user.model
import android.net.Uri
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.example.pmuapp.R
import java.io.Serializable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import androidx.room.Relation
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true)
val id: Int,
val name: String,
val login: String,
val password: String,
val petId: List<Pet>,
val imageResId: String // Добавляем поле для хранения ID ресурса изображения пользователя
) : Serializable
class UserViewModel : ViewModel() {
val imageUri: Uri = Uri.parse("android.resource://com.example.pmuapp/${R.drawable.avatar}")
var users: MutableState<List<User>> = mutableStateOf(
listOf(
User(0,"Иван", "ivan", "111111", emptyList(),imageUri.toString()),
User(1,"Анна", "ann", "111111", emptyList(),imageUri.toString()),
User(2,"Лиза", "liza", "111111",emptyList(),imageUri.toString())
@Relation(
entity = Pet::class,
parentColumn = "id",
entityColumn = "user_id"
)
)
val availablePetImages: List<Int> = listOf(
R.drawable.pet1,
R.drawable.pet2,
R.drawable.pet3,
R.drawable.pet4,
R.drawable.pet5,
R.drawable.pet6,
R.drawable.pet7,
R.drawable.pet8,
)
fun getUsers(): List<User> {
return users.value
val pets: List<Pet>,
@ColumnInfo(name = "image_res_id")
val imageResId: String
) {
@Ignore
constructor(id: Int, name: String, login: String, password: String, imageResId: Int) :
this(id, name, login, password, emptyList(), imageResId)
fun addPet(pet: Pet): User {
val updatedPets = pets.toMutableList()
updatedPets.add(pet)
return copy(pets = updatedPets)
}
fun getUser(id:Int): User {
return users.value.get(id)
}
fun getPets(id:Int): List<Pet> {
return users.value.get(id).petId
}
// Function to add a pet to a user
fun addPetToUser(userId: Int, newPet: Pet) {
val updatedUsers = users.value.toMutableList()
val user = updatedUsers.find { it.id == userId }
user?.let {
val updatedPets = user.petId.toMutableList()
updatedPets.add(newPet)
val updatedUser = user.copy(petId = updatedPets)
val userIndex = updatedUsers.indexOf(user)
updatedUsers[userIndex] = updatedUser
users.value = updatedUsers
}
}
fun deletePet(userId: Int, petIdToDelete: Int) {
val updatedUsers = users.value.toMutableList()
// Найдем пользователя по userId
val user = updatedUsers.find { it.id == userId }
user?.let { user ->
val updatedPets = user.petId.toMutableList()
// Найдем питомца по petId и удалим его из списка питомцев
val petToDelete = updatedPets.find { it.id == petIdToDelete }
petToDelete?.let { pet ->
updatedPets.remove(pet)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as User
if (id != other.id) return false
return true
}
// Обновим пользователя с обновленным списком питомцев
val updatedUser = user.copy(petId = updatedPets)
// Обновим список пользователей
val userIndex = updatedUsers.indexOf(user)
updatedUsers[userIndex] = updatedUser
users.value = updatedUsers
}
}
fun updatePetOnUser(userId: Int, updatedPet: Pet) {
val updatedUsers = users.value.toMutableList()
// Найдем пользователя по userId
val user = updatedUsers.find { it.id == userId }
user?.let { user ->
val updatedPets = user.petId.toMutableList()
// Найдем питомца по petId и обновим его
val petToUpdate = updatedPets.find { it.id == updatedPet.id }
petToUpdate?.let { pet ->
val petIndex = updatedPets.indexOf(pet)
updatedPets[petIndex] = updatedPet
}
// Обновим пользователя с обновленным списком питомцев
val updatedUser = user.copy(petId = updatedPets)
// Обновим список пользователей
val userIndex = updatedUsers.indexOf(user)
updatedUsers[userIndex] = updatedUser
users.value = updatedUsers
}
}
fun updateUser(updatedUser: User) {
val updatedUsers = users.value.toMutableList()
val index = updatedUsers.indexOfFirst { it.login == updatedUser.login }
if (index != -1) {
updatedUsers[index] = updatedUser
users.value = updatedUsers
}
override fun hashCode(): Int {
return id ?: -1
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 154 KiB

View File

@ -1,5 +1,8 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id("com.android.application") version "8.1.1" apply false
id("org.jetbrains.kotlin.android") version "1.8.10" apply false
id("com.android.application") version "8.1.2" apply false
id("org.jetbrains.kotlin.android") version "1.8.20" apply false
id("com.google.devtools.ksp") version "1.8.20-1.0.11" apply false
}

View File

@ -21,4 +21,3 @@ kotlin.code.style=official
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.overridePathCheck=true