Compare commits

..

4 Commits

21 changed files with 551 additions and 135 deletions

View File

@ -80,4 +80,8 @@ 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,6 +3,7 @@
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,6 +48,7 @@ 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
@ -109,3 +110,25 @@ 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

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

@ -0,0 +1,27 @@
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,6 +15,7 @@ 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
@ -67,3 +68,52 @@ 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 = "Иван", password = "1234",)) userDao.insert(User(id = 1, login = "Margen", password = "1234",))
userDao.insert(User(id = 2, login = "Леонель Месси", password = "4321",)) userDao.insert(User(id = 2, login = "Leonel Messi", password = "4321",))
val cardDao = database.cardDao() val cardDao = database.cardDao()
cardDao.insert( cardDao.insert(

View File

@ -1,5 +1,6 @@
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
@ -12,13 +13,13 @@ import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface CardDao { interface CardDao {
@Query("select * from cards") @Query("select * from cards")
fun getAll(): Flow<List<Card>> fun getAll(): PagingSource<Int, Card>
@Query("select * from cards where cards.id = :id") @Query("select * from cards where cards.id = :id")
fun getById(id: Int): Card? fun getById(id: Int): Flow<Card?>
@Query("select * from cards where cards.user_id = :userId") @Query("select * from cards where cards.user_id = :userId")
fun getByUserId(userId: Int): Flow<List<Card>> fun getByUserId(userId: Int): PagingSource<Int, Card>
@Insert(onConflict = OnConflictStrategy.IGNORE) @Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(card: Card) suspend fun insert(card: Card)

View File

@ -19,7 +19,10 @@ 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): User? fun getById(id: Int): Flow<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)
@ -29,4 +32,8 @@ 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

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

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

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

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

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

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

@ -0,0 +1,53 @@
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,7 +14,9 @@ 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
@ -25,32 +27,33 @@ 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 = remember { mutableStateListOf<User>() } val users = userViewModel.getAllUsers.collectAsState(emptyList()).value
val login = remember { mutableStateOf("") }
LaunchedEffect(Unit) { val password = remember { mutableStateOf("") }
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
@ -73,11 +76,26 @@ fun Authorization(navController: NavHostController){
fontSize = 20.sp fontSize = 20.sp
) )
} }
LoginField(text = "Логин") PlaceholderInputFieldAuth(label = "Логин", isSingleLine = true, onTextChanged = { newlogin ->
PasswordField(text = "Пароль") login.value = newlogin
navButton(navController = navController, destination = "mainScreen", label = "Вход", })
backgroundColor = Color.Cyan, textColor = Color.Black) PasswordInputField(label = "Пароль", onPasswordChanged = { newpassword ->
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 = Color.Cyan, textColor = Color.Black) backgroundColor = SkyBlue, textColor = Color.Black)
} }
} }

View File

@ -35,8 +35,10 @@ 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
@ -45,12 +47,19 @@ 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, cardId: Int? = null) { fun EditCardScreen(navController: NavHostController,
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)) }
@ -76,52 +85,26 @@ fun EditCardScreen(navController: NavHostController, cardId: Int? = null) {
} }
} }
cardId?.let{
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
val card = MobileAppDataBase.getInstance(context).cardDao().getById(cardId!!)
image.value = card!!.image
name.value = card!!.name
location.value = card!!.location
price.value = card!!.price
mileage.value = card!!.mileage
}
}
}
val edit = remember { mutableStateOf(false) }
if (edit.value){
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
cardId?.let { cardId?.let {
MobileAppDataBase.getInstance(context).cardDao() cardViewModel.getCardById(cardId).collect {
.update( if (it != null) {
Card( image.value = it.image
id = cardId, }
name = name.value, if (it != null) {
location = location.value, name.value = it.name
price = price.value, }
mileage = mileage.value, if (it != null) {
image = image.value, location.value = it.location
userId = 1) }
) if (it != null) {
mileage.value = it.mileage
} ?: run { }
MobileAppDataBase.getInstance(context).cardDao() if (it != null) {
.insert( price.value = it.price
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(
@ -160,34 +143,52 @@ fun EditCardScreen(navController: NavHostController, cardId: Int? = null) {
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 = {
edit.value = !edit.value cardId?.let {
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
val photo = remember { mutableStateOf<Bitmap>(BitmapFactory.decodeResource(context.resources, R.drawable.login)) } var userId = remember { mutableStateOf(0) }
val name = remember { mutableStateOf("") } val login = 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)
} else { LaunchedEffect(Unit) {
val source = ImageDecoder GlobalUser.getInstance().getUser()?.let { user ->
.createSource(context.contentResolver, imageData.value!!) userId.value = user!!.id!!
photo.value = ImageDecoder.decodeBitmap(source) login.value = user!!.login
password.value = user!!.password
} }
} }
@ -197,27 +198,23 @@ fun EditUserScreen(navController: NavHostController){
.padding(bottom = 8.dp), .padding(bottom = 8.dp),
verticalArrangement = Arrangement.Bottom verticalArrangement = Arrangement.Bottom
) { ) {
Image( PlaceholderInputField(label = "Логин", isSingleLine = true,
bitmap = photo.value.asImageBitmap(), startValue = login.value, onTextChanged = { newName ->
contentDescription = "editplaceholder", login.value = newName
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 = {
//edit.value = !edit.value userViewModel.updateUser(
User(
id = userId.value,
login = login.value,
password = password.value,
)
)
navController.navigate("userSettings")
}) })
} }
} }

View File

@ -37,6 +37,8 @@ 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
@ -49,27 +51,25 @@ 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>() }
LaunchedEffect(Unit) { val cards = cardViewModel.getAllCards.collectAsLazyPagingItems()
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,7 +77,22 @@ fun MainScreen(navController: NavHostController) {
.fillMaxHeight(0.9f)) { .fillMaxHeight(0.9f)) {
Column() Column()
{ {
DataListScroll(navController, cards) LazyVerticalGrid(
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,31 +4,61 @@ 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) {
Text(text = "Привет!", PlaceholderInputFieldAuth(label = "Логин", isSingleLine = true, onTextChanged = {newlogin ->
fontSize = 20.sp, login.value = newlogin
fontWeight = FontWeight.Bold) })
Text(text = "Зарегистрируйся, чтобы начать!", PasswordInputField(label = "Пароль", onPasswordChanged = {newpassword ->
fontSize = 20.sp, password.value = newpassword
fontWeight = FontWeight.Bold) })
LoginField(text = "Логин") PasswordInputField(label = "Повторите пароль", onPasswordChanged = {newpassword ->
PasswordField(text = "Пароль") repeatepassword.value = newpassword
PasswordField(text = "Повторите пароль") })
navButton(navController = navController, destination = "authorization", label = "Зарегистрироваться", backgroundColor = Color.Cyan, textColor = Color.Black) ActiveButton(label = "Зарегистрироваться", backgroundColor = SkyBlue,
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,35 +19,47 @@ 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 = 1 val userId = GlobalUser.getInstance().getUser()?.id?: 1
userId?.let {
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
withContext(Dispatchers.IO) { userId?.let {
val user = MobileAppDataBase.getInstance(context).userDao().getById(userId!!) userViewModel.getUser(userId).collect {
login.value = user!!.login if (it != null) {
password.value = user!!.password login.value = it.login
}
if (it != null) {
password.value = it.password
}
} }
} }
} }
@ -65,8 +77,18 @@ fun UserSettings(navController: NavHostController) {
modifier = Modifier modifier = Modifier
.size(300.dp) .size(300.dp)
) )
LoginField(text = "Логин пользователя: ${login.value}") PlaceholderInputField(label = "Логин пользователя: ${login.value}", isSingleLine = true, onTextChanged = {newlogin ->
LoginField(text = "Пароль пользователя: ${password.value}") login.value = newlogin})
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