Compare commits

..

No commits in common. "1ebf64982f0fdf6985c484780b259d5cab5e93ec" and "f1c0642cf784f2287dcc0623a08ef39eda0d787b" have entirely different histories.

21 changed files with 135 additions and 551 deletions

View File

@ -80,8 +80,4 @@ dependencies {
ksp("androidx.room:room-compiler:$room_version") ksp("androidx.room:room-compiler:$room_version")
implementation("androidx.room:room-ktx:$room_version") implementation("androidx.room:room-ktx:$room_version")
implementation("androidx.room:room-paging:$room_version") implementation("androidx.room:room-paging:$room_version")
//Paging
implementation ("androidx.paging:paging-compose:3.2.1")
implementation ("androidx.paging:paging-runtime:3.2.1")
} }

View File

@ -3,7 +3,6 @@
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<application <application
android:name=".MobileApp"
android:allowBackup="true" android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules" android:fullBackupContent="@xml/backup_rules"

View File

@ -48,7 +48,6 @@ import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument import androidx.navigation.navArgument
import com.example.myapplication.database.MobileAppDataBase import com.example.myapplication.database.MobileAppDataBase
import com.example.myapplication.database.entities.User
import com.example.myapplication.screens.Authorization import com.example.myapplication.screens.Authorization
import com.example.myapplication.screens.EditCardScreen import com.example.myapplication.screens.EditCardScreen
import com.example.myapplication.screens.EditUserScreen import com.example.myapplication.screens.EditUserScreen
@ -110,25 +109,3 @@ fun AppNavigation(navController: NavHostController){
} }
} }
} }
class GlobalUser private constructor() {
private var user: User? = null
fun setUser(user: User?) {
this.user = user
}
fun getUser(): User? {
return user
}
companion object {
private var instance: GlobalUser? = null
fun getInstance(): GlobalUser {
return instance ?: synchronized(this) {
instance ?: GlobalUser().also { instance = it }
}
}
}
}

View File

@ -1,12 +0,0 @@
package com.example.myapplication
import android.app.Application
class MobileApp: Application() {
lateinit var container: MobileAppContainer
override fun onCreate() {
super.onCreate()
container = MobileAppDataContainer(this)
}
}

View File

@ -1,27 +0,0 @@
package com.example.myapplication
import android.content.Context
import com.example.myapplication.database.MobileAppDataBase
import com.example.myapplication.database.repositories.CardRepository
import com.example.myapplication.database.repositories.OfflineCardRepository
import com.example.myapplication.database.repositories.OfflineUserRepository
import com.example.myapplication.database.repositories.UserRepository
interface MobileAppContainer {
val cardRepository: CardRepository
val userRepository: UserRepository
}
class MobileAppDataContainer(private val context: Context): MobileAppContainer {
override val cardRepository: CardRepository by lazy {
OfflineCardRepository(MobileAppDataBase.getInstance(context).cardDao())
}
override val userRepository: UserRepository by lazy {
OfflineUserRepository(MobileAppDataBase.getInstance(context).userDao())
}
companion object{
const val TIMEOUT = 5000L
}
}

View File

@ -15,7 +15,6 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
@ -68,52 +67,3 @@ fun ActiveButton(label: String, backgroundColor: Color, textColor: Color, onClic
) )
} }
} }
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlaceholderInputFieldAuth(label: String, startValue: String? = null, isSingleLine: Boolean, onTextChanged: (String) -> Unit){
var text = remember { mutableStateOf("") }
startValue?.let{
text.value = startValue
}
OutlinedTextField(
value = text.value,
onValueChange = {
text.value = it
onTextChanged(it)
},
placeholder = {
Text(label)
},
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp, start = 16.dp, bottom = 8.dp, end = 16.dp),
shape = RoundedCornerShape(10.dp),
singleLine = isSingleLine
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PasswordInputField(label: String, startValue: String? = null, onPasswordChanged: (String) -> Unit){
var text = remember { mutableStateOf("") }
startValue?.let{
text.value = startValue
}
OutlinedTextField(
value = text.value,
onValueChange = {
text.value = it
onPasswordChanged(it)
},
placeholder = {
Text(label)
},
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp, start = 16.dp, bottom = 8.dp, end = 16.dp),
shape = RoundedCornerShape(10.dp))
}

View File

@ -53,8 +53,8 @@ abstract class MobileAppDataBase : RoomDatabase() {
private suspend fun initialDataBase(appContext: Context) { private suspend fun initialDataBase(appContext: Context) {
INSTANCE?.let { database -> INSTANCE?.let { database ->
val userDao = database.userDao() val userDao = database.userDao()
userDao.insert(User(id = 1, login = "Margen", password = "1234",)) userDao.insert(User(id = 1, login = "Иван", password = "1234",))
userDao.insert(User(id = 2, login = "Leonel Messi", password = "4321",)) userDao.insert(User(id = 2, login = "Леонель Месси", password = "4321",))
val cardDao = database.cardDao() val cardDao = database.cardDao()
cardDao.insert( cardDao.insert(

View File

@ -1,6 +1,5 @@
package com.example.myapplication.database.dao package com.example.myapplication.database.dao
import androidx.paging.PagingSource
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
@ -13,13 +12,13 @@ import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface CardDao { interface CardDao {
@Query("select * from cards") @Query("select * from cards")
fun getAll(): PagingSource<Int, Card> fun getAll(): Flow<List<Card>>
@Query("select * from cards where cards.id = :id") @Query("select * from cards where cards.id = :id")
fun getById(id: Int): Flow<Card?> fun getById(id: Int): Card?
@Query("select * from cards where cards.user_id = :userId") @Query("select * from cards where cards.user_id = :userId")
fun getByUserId(userId: Int): PagingSource<Int, Card> fun getByUserId(userId: Int): Flow<List<Card>>
@Insert(onConflict = OnConflictStrategy.IGNORE) @Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(card: Card) suspend fun insert(card: Card)

View File

@ -19,10 +19,7 @@ interface UserDao {
fun getAll(): Flow<List<User>> fun getAll(): Flow<List<User>>
@Query("select * from users where users.id = :id") @Query("select * from users where users.id = :id")
fun getById(id: Int): Flow<User?> fun getById(id: Int): User?
@Query("select * from users where users.login = :login")
suspend fun getByLogin(login: String): User?
@Insert(onConflict = OnConflictStrategy.IGNORE) @Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(user: User) suspend fun insert(user: User)
@ -32,8 +29,4 @@ interface UserDao {
@Delete @Delete
suspend fun delete(user: User) suspend fun delete(user: User)
@Query("SELECT * FROM users WHERE login = :login AND password = :password")
fun getUserByLoginAndPassword(login: String, password: String): User?
} }

View File

@ -1,19 +0,0 @@
package com.example.myapplication.database.repositories
import androidx.paging.PagingData
import com.example.myapplication.database.entities.Card
import kotlinx.coroutines.flow.Flow
interface CardRepository {
fun getAllCards(): Flow<PagingData<Card>>
fun getCardsByUserId(userId: Int): Flow<PagingData<Card>>
fun getCardById(id: Int): Flow<Card?>
suspend fun insertCard(card: Card)
suspend fun updateCard(card: Card)
suspend fun deleteCard(card: Card)
}

View File

@ -1,49 +0,0 @@
package com.example.myapplication.database.repositories
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.myapplication.database.dao.CardDao
import com.example.myapplication.database.entities.Card
import kotlinx.coroutines.flow.Flow
class OfflineCardRepository(private val cardDao: CardDao): CardRepository {
override fun getAllCards(): Flow<PagingData<Card>> {
return Pager(
config = PagingConfig(
pageSize = 5,
prefetchDistance = 1,
enablePlaceholders = true,
initialLoadSize = 10,
maxSize = 15
),
pagingSourceFactory = {
cardDao.getAll()
}
).flow
}
override fun getCardsByUserId(UserId: Int):Flow<PagingData<Card>> {
return Pager(
config = PagingConfig(
pageSize = 5,
prefetchDistance = 1,
enablePlaceholders = true,
initialLoadSize = 10,
maxSize = 15
),
pagingSourceFactory = {
cardDao.getByUserId(UserId)
}
).flow
}
override fun getCardById(id: Int): Flow<Card?> = cardDao.getById(id)
override suspend fun insertCard(card: Card) = cardDao.insert(card)
override suspend fun updateCard(card: Card) = cardDao.update(card)
override suspend fun deleteCard(card: Card) = cardDao.delete(card)
}

View File

@ -1,21 +0,0 @@
package com.example.myapplication.database.repositories
import com.example.myapplication.database.dao.UserDao
import com.example.myapplication.database.entities.User
import kotlinx.coroutines.flow.Flow
class OfflineUserRepository(private val userDao: UserDao): UserRepository {
override fun getAllUsers(): Flow<List<User>> = userDao.getAll()
override suspend fun getUserById(id: Int): Flow<User?> = userDao.getById(id)
override suspend fun getUserByLogin(login: String): User? = userDao.getByLogin(login)
override suspend fun insertUser(user: User) = userDao.insert(user)
override suspend fun updateUser(user: User) = userDao.update(user)
override suspend fun deleteUser(user: User) = userDao.delete(user)
override suspend fun getUserByLoginAndPassword(login: String, password: String): User? = userDao.getUserByLoginAndPassword(login, password)
}

View File

@ -1,21 +0,0 @@
package com.example.myapplication.database.repositories
import androidx.room.Query
import com.example.myapplication.database.entities.User
import kotlinx.coroutines.flow.Flow
interface UserRepository {
fun getAllUsers(): Flow<List<User>>
suspend fun getUserById(id: Int): Flow<User?>
suspend fun getUserByLogin(login: String): User?
suspend fun insertUser(user: User)
suspend fun updateUser(user: User)
suspend fun deleteUser(user: User)
suspend fun getUserByLoginAndPassword(login: String, password: String): User?
}

View File

@ -1,25 +0,0 @@
package com.example.myapplication.database.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.myapplication.database.dao.CardDao
import com.example.myapplication.database.entities.Card
import com.example.myapplication.database.repositories.CardRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
class CardViewModel(private val cardRepository : CardRepository):ViewModel() {
val getAllCards: Flow<PagingData<Card>> = cardRepository.getAllCards().cachedIn(viewModelScope)
fun getCardById(id: Int): Flow<Card?> = cardRepository.getCardById(id)
fun getCardByUserId(userId: Int): Flow<PagingData<Card>> = cardRepository.getCardsByUserId(userId).cachedIn(viewModelScope)
fun insertCard(card: Card) = viewModelScope.launch { cardRepository.insertCard(card) }
fun updateCard(card: Card) = viewModelScope.launch { cardRepository.updateCard(card) }
fun deleteCard(card: Card) = viewModelScope.launch { cardRepository.deleteCard(card) }
}

View File

@ -1,21 +0,0 @@
package com.example.myapplication.database.viewmodels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.myapplication.MobileApp
object MobileAppViewModelProvider {
val Factory = viewModelFactory {
initializer {
CardViewModel(app().container.cardRepository)
}
initializer {
UserViewModel(app().container.userRepository)
}
}
}
fun CreationExtras.app(): MobileApp =
(this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as MobileApp)

View File

@ -1,53 +0,0 @@
package com.example.myapplication.database.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.GlobalUser
import com.example.myapplication.database.entities.User
import com.example.myapplication.database.repositories.UserRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
class UserViewModel(private val userRepository: UserRepository): ViewModel() {
val getAllUsers = userRepository.getAllUsers()
suspend fun getUser(id: Int): Flow<User?> = userRepository.getUserById(id)
fun updateUser(user: User) = viewModelScope.launch {
userRepository.updateUser(user)
}
fun deleteUser(user: User) = viewModelScope.launch {
userRepository.deleteUser(user)
}
suspend fun getUserByLogin(login: String): User? = userRepository.getUserByLogin(login)
fun regUser(user: User) = viewModelScope.launch {
val globalUser = userRepository.getUserByLogin(user.login)
globalUser?.let {
return@launch
} ?: run {
if(user.password.isEmpty()){
return@launch
}
userRepository.insertUser(user)
GlobalUser.getInstance().setUser(userRepository.getUserByLogin(user.login))
}
}
fun authUser(user: User) = viewModelScope.launch {
val globalUser = userRepository.getUserByLogin(user.login)
if (user.password.isNotEmpty() && user.password == globalUser?.password){
GlobalUser.getInstance().setUser(globalUser)
val user123 = GlobalUser.getInstance().getUser()
println(user123)
}
}
private fun isValidEmail(email: String): Boolean {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
}

View File

@ -14,9 +14,7 @@ import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@ -27,33 +25,32 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.example.myapplication.R import com.example.myapplication.R
import com.example.myapplication.components.ActiveButton
import com.example.myapplication.components.LoginField import com.example.myapplication.components.LoginField
import com.example.myapplication.components.PasswordField import com.example.myapplication.components.PasswordField
import com.example.myapplication.components.PasswordInputField
import com.example.myapplication.components.PlaceholderInputField
import com.example.myapplication.components.PlaceholderInputFieldAuth
import com.example.myapplication.components.navButton import com.example.myapplication.components.navButton
import com.example.myapplication.database.MobileAppDataBase import com.example.myapplication.database.MobileAppDataBase
import com.example.myapplication.database.entities.Card import com.example.myapplication.database.entities.Card
import com.example.myapplication.database.entities.User import com.example.myapplication.database.entities.User
import com.example.myapplication.database.viewmodels.MobileAppViewModelProvider
import com.example.myapplication.database.viewmodels.UserViewModel
import com.example.myapplication.ui.theme.SkyBlue
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@Composable @Composable
fun Authorization(navController: NavHostController, fun Authorization(navController: NavHostController){
userViewModel: UserViewModel = viewModel( factory = MobileAppViewModelProvider.Factory )){
val context = LocalContext.current val context = LocalContext.current
val users = userViewModel.getAllUsers.collectAsState(emptyList()).value val users = remember { mutableStateListOf<User>() }
val login = remember { mutableStateOf("") }
val password = remember { mutableStateOf("") } LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
val database = MobileAppDataBase.getInstance(context)
database.userDao().getAll().collect { data ->
users.clear()
data.forEach { users.add(it) }
}
}
}
Column ( Column (
modifier = Modifier modifier = Modifier
@ -76,26 +73,11 @@ fun Authorization(navController: NavHostController,
fontSize = 20.sp fontSize = 20.sp
) )
} }
PlaceholderInputFieldAuth(label = "Логин", isSingleLine = true, onTextChanged = { newlogin -> LoginField(text = "Логин")
login.value = newlogin PasswordField(text = "Пароль")
}) navButton(navController = navController, destination = "mainScreen", label = "Вход",
PasswordInputField(label = "Пароль", onPasswordChanged = { newpassword -> backgroundColor = Color.Cyan, textColor = Color.Black)
password.value = newpassword
})
ActiveButton(label = "Вход", backgroundColor = SkyBlue,
textColor = Color.Black, onClickAction = {
if (login.value.isNotEmpty() && password.value.isNotEmpty()) {
userViewModel.authUser(
User(
login = login.value,
password = password.value,
)
)
navController.navigate("mainScreen")
}
})
navButton(navController = navController, destination = "registration", label = "Регистрация", navButton(navController = navController, destination = "registration", label = "Регистрация",
backgroundColor = SkyBlue, textColor = Color.Black) backgroundColor = Color.Cyan, textColor = Color.Black)
} }
} }

View File

@ -35,10 +35,8 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.example.myapplication.GlobalUser
import com.example.myapplication.R import com.example.myapplication.R
import com.example.myapplication.components.ActiveButton import com.example.myapplication.components.ActiveButton
import com.example.myapplication.components.LoginField import com.example.myapplication.components.LoginField
@ -47,19 +45,12 @@ import com.example.myapplication.components.navBar
import com.example.myapplication.components.navButton import com.example.myapplication.components.navButton
import com.example.myapplication.database.MobileAppDataBase import com.example.myapplication.database.MobileAppDataBase
import com.example.myapplication.database.entities.Card import com.example.myapplication.database.entities.Card
import com.example.myapplication.database.entities.User
import com.example.myapplication.database.viewmodels.CardViewModel
import com.example.myapplication.database.viewmodels.MobileAppViewModelProvider
import com.example.myapplication.database.viewmodels.UserViewModel
import com.example.myapplication.ui.theme.SkyBlue import com.example.myapplication.ui.theme.SkyBlue
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlin.math.log
@Composable @Composable
fun EditCardScreen(navController: NavHostController, fun EditCardScreen(navController: NavHostController, cardId: Int? = null) {
cardViewModel: CardViewModel = viewModel( factory = MobileAppViewModelProvider.Factory),
cardId: Int? = null) {
val context = LocalContext.current val context = LocalContext.current
val image = remember { mutableStateOf<Bitmap>(BitmapFactory.decodeResource(context.resources, R.drawable.ferrari_laferrari_car2)) } val image = remember { mutableStateOf<Bitmap>(BitmapFactory.decodeResource(context.resources, R.drawable.ferrari_laferrari_car2)) }
@ -85,26 +76,52 @@ fun EditCardScreen(navController: NavHostController,
} }
} }
LaunchedEffect(Unit) { cardId?.let{
cardId?.let { LaunchedEffect(Unit) {
cardViewModel.getCardById(cardId).collect { withContext(Dispatchers.IO) {
if (it != null) { val card = MobileAppDataBase.getInstance(context).cardDao().getById(cardId!!)
image.value = it.image image.value = card!!.image
} name.value = card!!.name
if (it != null) { location.value = card!!.location
name.value = it.name price.value = card!!.price
} mileage.value = card!!.mileage
if (it != null) { }
location.value = it.location }
} }
if (it != null) {
mileage.value = it.mileage val edit = remember { mutableStateOf(false) }
} if (edit.value){
if (it != null) { LaunchedEffect(Unit) {
price.value = it.price withContext(Dispatchers.IO) {
cardId?.let {
MobileAppDataBase.getInstance(context).cardDao()
.update(
Card(
id = cardId,
name = name.value,
location = location.value,
price = price.value,
mileage = mileage.value,
image = image.value,
userId = 1)
)
} ?: run {
MobileAppDataBase.getInstance(context).cardDao()
.insert(
Card(
name = name.value,
location = location.value,
price = price.value,
mileage = mileage.value,
image = image.value,
userId = 1)
)
} }
} }
} }
edit.value = !edit.value
navController.navigate("mainScreen")
} }
Column( Column(
@ -143,52 +160,34 @@ fun EditCardScreen(navController: NavHostController,
price.value = newPrice.toIntOrNull() ?: 10000 price.value = newPrice.toIntOrNull() ?: 10000
}) })
ActiveButton(label = "Сохранить", backgroundColor = SkyBlue, textColor = Color.Black, onClickAction = { ActiveButton(label = "Сохранить", backgroundColor = SkyBlue, textColor = Color.Black, onClickAction = {
cardId?.let { edit.value = !edit.value
cardViewModel.updateCard(
Card(
id = cardId,
image = image.value,
name = name.value,
location = location.value,
mileage = mileage.value,
price = price.value,
userId = GlobalUser.getInstance().getUser()?.id ?: 1
)
)
} ?: run {
cardViewModel.insertCard(
Card(
image = image.value,
name = name.value,
location = location.value,
mileage = mileage.value,
price = price.value,
userId = GlobalUser.getInstance().getUser()?.id ?: 1
)
)
}
navController.navigate("mainScreen")
}) })
navButton(navController = navController, destination = "mainScreen", label = "Назад", backgroundColor = SkyBlue, textColor = Color.Black) navButton(navController = navController, destination = "mainScreen", label = "Назад", backgroundColor = SkyBlue, textColor = Color.Black)
} }
} }
@Composable @Composable
fun EditUserScreen(navController: NavHostController, fun EditUserScreen(navController: NavHostController){
userViewModel: UserViewModel = viewModel(
factory = MobileAppViewModelProvider.Factory)){
val context = LocalContext.current val context = LocalContext.current
var userId = remember { mutableStateOf(0) } val photo = remember { mutableStateOf<Bitmap>(BitmapFactory.decodeResource(context.resources, R.drawable.login)) }
val login = remember { mutableStateOf("") } val name = remember { mutableStateOf("") }
val password = remember { mutableStateOf("") } val password = remember { mutableStateOf("") }
val imageData = remember { mutableStateOf<Uri?>(null) }
val launcher =
rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) {uri: Uri? ->
imageData.value = uri
}
imageData.value?.let {
if (Build.VERSION.SDK_INT < 28) {
photo.value = MediaStore.Images
.Media.getBitmap(context.contentResolver, imageData.value)
LaunchedEffect(Unit) { } else {
GlobalUser.getInstance().getUser()?.let { user -> val source = ImageDecoder
userId.value = user!!.id!! .createSource(context.contentResolver, imageData.value!!)
login.value = user!!.login photo.value = ImageDecoder.decodeBitmap(source)
password.value = user!!.password
} }
} }
@ -198,23 +197,27 @@ fun EditUserScreen(navController: NavHostController,
.padding(bottom = 8.dp), .padding(bottom = 8.dp),
verticalArrangement = Arrangement.Bottom verticalArrangement = Arrangement.Bottom
) { ) {
PlaceholderInputField(label = "Логин", isSingleLine = true, Image(
startValue = login.value, onTextChanged = { newName -> bitmap = photo.value.asImageBitmap(),
login.value = newName contentDescription = "editplaceholder",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(384.dp)
.padding(8.dp)
.align(Alignment.CenterHorizontally))
ActiveButton(label = "Выбрать фото", backgroundColor = SkyBlue, textColor = Color.Black, onClickAction = {
launcher.launch("image/*")
})
PlaceholderInputField(label = "Никнейм", isSingleLine = true,
startValue = name.value, onTextChanged = { newName ->
name.value = newName
}) })
PlaceholderInputField(label = "Пароль", isSingleLine = true, PlaceholderInputField(label = "Пароль", isSingleLine = true,
startValue = password.value, onTextChanged = { newPassword -> startValue = password.value, onTextChanged = { newPassword ->
password.value = newPassword password.value = newPassword
}) })
ActiveButton(label = "Сохранить", backgroundColor = SkyBlue, textColor = Color.Black, onClickAction = { ActiveButton(label = "Сохранить", backgroundColor = SkyBlue, textColor = Color.Black, onClickAction = {
userViewModel.updateUser( //edit.value = !edit.value
User(
id = userId.value,
login = login.value,
password = password.value,
)
)
navController.navigate("userSettings")
}) })
} }
} }

View File

@ -37,8 +37,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
@ -51,25 +49,27 @@ import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateListOf
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.myapplication.GlobalUser
import com.example.myapplication.R import com.example.myapplication.R
import com.example.myapplication.database.MobileAppDataBase import com.example.myapplication.database.MobileAppDataBase
import com.example.myapplication.database.viewmodels.CardViewModel
import com.example.myapplication.database.viewmodels.MobileAppViewModelProvider
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@Composable @Composable
fun MainScreen(navController: NavHostController, fun MainScreen(navController: NavHostController) {
cardViewModel: CardViewModel = viewModel(factory = MobileAppViewModelProvider.Factory)) {
val context = LocalContext.current val context = LocalContext.current
val cards = remember { mutableStateListOf<Card>() }
val cards = cardViewModel.getAllCards.collectAsLazyPagingItems() LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
val database = MobileAppDataBase.getInstance(context)
database.cardDao().getAll().collect { data ->
cards.clear()
data.forEach { cards.add(it) }
}
}
}
Column { Column {
Box(modifier = Modifier Box(modifier = Modifier
@ -77,22 +77,7 @@ fun MainScreen(navController: NavHostController,
.fillMaxHeight(0.9f)) { .fillMaxHeight(0.9f)) {
Column() Column()
{ {
LazyVerticalGrid( DataListScroll(navController, cards)
columns = GridCells.Fixed(1)
) {
item {
addNewListItem(navController, "editcard")
}
items(
count = cards.itemCount,
key = cards.itemKey { item -> item.id!! }
) { index: Int ->
val card: Card? = cards[index]
if (card != null) {
CardListItem(item = card, navController = navController)
}
}
}
} }
} }
Column( Column(

View File

@ -4,61 +4,31 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ModifierInfo import androidx.compose.ui.layout.ModifierInfo
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.example.myapplication.components.ActiveButton
import com.example.myapplication.components.LoginField import com.example.myapplication.components.LoginField
import com.example.myapplication.components.PasswordField import com.example.myapplication.components.PasswordField
import com.example.myapplication.components.PasswordInputField
import com.example.myapplication.components.PlaceholderInputField
import com.example.myapplication.components.PlaceholderInputFieldAuth
import com.example.myapplication.components.navButton import com.example.myapplication.components.navButton
import com.example.myapplication.database.entities.User
import com.example.myapplication.database.viewmodels.MobileAppViewModelProvider
import com.example.myapplication.database.viewmodels.UserViewModel
import com.example.myapplication.ui.theme.SkyBlue
@Composable @Composable
fun Registration(navController: NavHostController, fun Registration(navController: NavHostController) {
userViewModel: UserViewModel = viewModel(
factory = MobileAppViewModelProvider.Factory)) {
val login = remember { mutableStateOf("") }
val password = remember { mutableStateOf("") }
val repeatepassword = remember { mutableStateOf("") }
Column (modifier = Modifier.fillMaxWidth(), Column (modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally) { horizontalAlignment = Alignment.CenterHorizontally) {
PlaceholderInputFieldAuth(label = "Логин", isSingleLine = true, onTextChanged = {newlogin -> Text(text = "Привет!",
login.value = newlogin fontSize = 20.sp,
}) fontWeight = FontWeight.Bold)
PasswordInputField(label = "Пароль", onPasswordChanged = {newpassword -> Text(text = "Зарегистрируйся, чтобы начать!",
password.value = newpassword fontSize = 20.sp,
}) fontWeight = FontWeight.Bold)
PasswordInputField(label = "Повторите пароль", onPasswordChanged = {newpassword -> LoginField(text = "Логин")
repeatepassword.value = newpassword PasswordField(text = "Пароль")
}) PasswordField(text = "Повторите пароль")
ActiveButton(label = "Зарегистрироваться", backgroundColor = SkyBlue, navButton(navController = navController, destination = "authorization", label = "Зарегистрироваться", backgroundColor = Color.Cyan, textColor = Color.Black)
textColor = Color.Black, onClickAction = {
if (password.value == repeatepassword.value){
userViewModel.regUser(
User(
login = login.value,
password = password.value,
)
)
}
navController.navigate("authorization")
})
navButton(navController = navController, destination = "authorization",
label = "Назад", backgroundColor = SkyBlue, textColor = Color.Black)
} }
} }

View File

@ -19,47 +19,35 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.example.myapplication.GlobalUser
import com.example.myapplication.MobileApp
import com.example.myapplication.R import com.example.myapplication.R
import com.example.myapplication.components.ActiveButton
import com.example.myapplication.components.LoginField import com.example.myapplication.components.LoginField
import com.example.myapplication.components.PlaceholderInputField
import com.example.myapplication.components.navBar import com.example.myapplication.components.navBar
import com.example.myapplication.database.MobileAppDataBase import com.example.myapplication.database.MobileAppDataBase
import com.example.myapplication.database.entities.Card
import com.example.myapplication.database.entities.User import com.example.myapplication.database.entities.User
import com.example.myapplication.database.viewmodels.MobileAppViewModelProvider
import com.example.myapplication.database.viewmodels.UserViewModel
import com.example.myapplication.ui.theme.SkyBlue import com.example.myapplication.ui.theme.SkyBlue
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@Composable @Composable
fun UserSettings(navController: NavHostController, fun UserSettings(navController: NavHostController) {
userViewModel: UserViewModel = viewModel(factory = MobileAppViewModelProvider.Factory)) {
val context = LocalContext.current val context = LocalContext.current
val login = remember { mutableStateOf("") } val login = remember { mutableStateOf("") }
val password = remember { mutableStateOf("") } val password = remember { mutableStateOf("") }
val userId = GlobalUser.getInstance().getUser()?.id?: 1 val userId = 1
LaunchedEffect(Unit) { userId?.let {
userId?.let { LaunchedEffect(Unit) {
userViewModel.getUser(userId).collect { withContext(Dispatchers.IO) {
if (it != null) { val user = MobileAppDataBase.getInstance(context).userDao().getById(userId!!)
login.value = it.login login.value = user!!.login
} password.value = user!!.password
if (it != null) {
password.value = it.password
}
} }
} }
} }
@ -69,7 +57,7 @@ fun UserSettings(navController: NavHostController,
Column( Column(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
Image( Image(
painter = painterResource(id = R.drawable.user), painter = painterResource(id = R.drawable.user),
contentDescription = "login", contentDescription = "login",
@ -77,18 +65,8 @@ fun UserSettings(navController: NavHostController,
modifier = Modifier modifier = Modifier
.size(300.dp) .size(300.dp)
) )
PlaceholderInputField(label = "Логин пользователя: ${login.value}", isSingleLine = true, onTextChanged = {newlogin -> LoginField(text = "Логин пользователя: ${login.value}")
login.value = newlogin}) LoginField(text = "Пароль пользователя: ${password.value}")
PlaceholderInputField(label = "Пароль пользователя: ${password.value}", isSingleLine = true, onTextChanged = {newpassword ->
password.value = newpassword})
ActiveButton(label = "Сохранить изменения", backgroundColor = SkyBlue, textColor = Color.Black, onClickAction =
{
userViewModel.updateUser(User(
id = userId,
login = login.value,
password = password.value
))
})
} }
} }
Column(modifier = Modifier Column(modifier = Modifier