Готово, почти. Не факт что сдам

This commit is contained in:
maxnes3 2023-12-09 04:43:14 +04:00
parent 06f8248c75
commit 530972ba22
17 changed files with 250 additions and 111 deletions

View File

@ -76,4 +76,8 @@ dependencies {
ksp("androidx.room:room-compiler:$room_version")
implementation("androidx.room:room-ktx:$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

@ -14,6 +14,8 @@ import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
@ -38,6 +40,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.itemKey
import com.example.mobileapp.R
import com.example.mobileapp.database.MobileAppDataBase
import com.example.mobileapp.database.entities.Mail
@ -82,6 +86,7 @@ inline fun <reified T> List<*>.isListOf(): Boolean {
@Composable
fun StoryListItem(item: Story, navController: NavHostController,
isReadOnly: Boolean? = false,
storyViewModel: StoryViewModel = viewModel(
factory = MobileAppViewModelProvider.Factory
)) {
@ -135,16 +140,24 @@ fun StoryListItem(item: Story, navController: NavHostController,
visible = isExpanded.value,
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
){
DataListItemButton("Изменить", ButtonColor2, Color.White, onClickAction = {
navController.navigate("editstory/${item.id}")
})
DataListItemButton("Удалить", Color.Red, Color.White, onClickAction = {
showDialog.value = !showDialog.value
})
if (isReadOnly!!){
DataListItemButton(label = "Подробнее", backgroundColor = ButtonColor2,
textColor = Color.White, onClickAction = {
})
}
else{
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
){
DataListItemButton("Изменить", ButtonColor2, Color.White, onClickAction = {
navController.navigate("editstory/${item.id}")
})
DataListItemButton("Удалить", Color.Red, Color.White, onClickAction = {
showDialog.value = !showDialog.value
})
}
}
}
}
@ -226,22 +239,10 @@ fun MailListItem(item: Mail){
visible = isExpanded.value,
modifier = Modifier.fillMaxWidth()
) {
Button(
onClick = { /* Действие при нажатии кнопки */ },
modifier = Modifier
.requiredHeight(64.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(10.dp),
colors = ButtonDefaults.buttonColors(
containerColor = ButtonColor2
)
) {
Text(
text = "Подробнее",
color = Color.White,
fontSize = 18.sp,
)
}
DataListItemButton(label = "Подробнее", backgroundColor = ButtonColor2,
textColor = Color.White, onClickAction = {
})
}
}
}

View File

@ -67,15 +67,19 @@ fun NavBar(navController: NavHostController) {
enter = slideInVertically(initialOffsetY = { it }),
exit = slideOutVertically(targetOffsetY = { it }),
content = {
TopAppBar(title = {
Text(
text = "Storyteller",
textAlign = TextAlign.Center,
fontFamily = FontFamily(Font(
R.font.irishgrover_regular, FontWeight.Bold
))
)
})
TopAppBar(
title = {
Text(
text = "Storyteller!",
textAlign = TextAlign.Center,
fontFamily = FontFamily(
Font(
R.font.irishgrover_regular, FontWeight.Bold
)
)
)
}
)
}
)
},

View File

@ -1,5 +1,6 @@
package com.example.mobileapp.database.dao
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
@ -7,12 +8,13 @@ import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.example.mobileapp.database.entities.Mail
import com.example.mobileapp.database.entities.Story
import kotlinx.coroutines.flow.Flow
@Dao
interface MailDao {
@Query("select * from mails")
fun getAll(): Flow<List<Mail>>
@Query("select * from mails order by id desc")
fun getAll(): PagingSource<Int, Mail>
@Query("select * from mails where mails.id = :id")
fun getById(id: Int): Flow<Mail?>

View File

@ -1,5 +1,6 @@
package com.example.mobileapp.database.dao
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
@ -11,14 +12,14 @@ import kotlinx.coroutines.flow.Flow
@Dao
interface StoryDao {
@Query("select * from stories")
fun getAll(): Flow<List<Story>>
@Query("select * from stories order by id desc")
fun getAll(): PagingSource<Int, Story>
@Query("select * from stories where stories.id = :id")
fun getById(id: Int): Flow<Story?>
@Query("select * from stories where stories.user_id = :userId")
fun getByUserId(userId: Int): Flow<List<Story>>
@Query("select * from stories where stories.user_id = :userId order by stories.id desc")
fun getByUserId(userId: Int): PagingSource<Int, Story>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(story: Story)

View File

@ -12,7 +12,7 @@ import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao {
@Query("select * from users")
fun getAll():Flow<List<User>>
fun getAll(): Flow<List<User>>
@Query("select * from users where users.id = :id")
suspend fun getById(id: Int): User?

View File

@ -1,10 +1,11 @@
package com.example.mobileapp.database.repositories
import androidx.paging.PagingData
import com.example.mobileapp.database.entities.Mail
import kotlinx.coroutines.flow.Flow
interface MailRepository {
fun getAllMails(): Flow<List<Mail>>
fun getAllMails(): Flow<PagingData<Mail>>
fun getMail(id: Int): Flow<Mail?>

View File

@ -1,11 +1,27 @@
package com.example.mobileapp.database.repositories
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.mobileapp.database.dao.MailDao
import com.example.mobileapp.database.entities.Mail
import kotlinx.coroutines.flow.Flow
class OfflineMailRepository(private val mailDao: MailDao): MailRepository {
override fun getAllMails(): Flow<List<Mail>> = mailDao.getAll()
override fun getAllMails(): Flow<PagingData<Mail>> {
return Pager(
config = PagingConfig(
pageSize = 8,
prefetchDistance = 2,
enablePlaceholders = true,
initialLoadSize = 12,
maxSize = 24
),
pagingSourceFactory = {
mailDao.getAll()
}
).flow
}
override fun getMail(id: Int): Flow<Mail?> = mailDao.getById(id)

View File

@ -1,13 +1,42 @@
package com.example.mobileapp.database.repositories
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.mobileapp.database.dao.StoryDao
import com.example.mobileapp.database.entities.Story
import kotlinx.coroutines.flow.Flow
class OfflineStoryRepository(private val storyDao: StoryDao): StoryRepository {
override fun getAllStories(): Flow<List<Story>> = storyDao.getAll()
override fun getAllStories(): Flow<PagingData<Story>> {
return Pager(
config = PagingConfig(
pageSize = 5,
prefetchDistance = 1,
enablePlaceholders = true,
initialLoadSize = 10,
maxSize = 15
),
pagingSourceFactory = {
storyDao.getAll()
}
).flow
}
override fun getStoriesByUserId(userId: Int): Flow<List<Story>> = storyDao.getByUserId(userId)
override fun getStoriesByUserId(userId: Int): Flow<PagingData<Story>> {
return Pager(
config = PagingConfig(
pageSize = 5,
prefetchDistance = 1,
enablePlaceholders = true,
initialLoadSize = 10,
maxSize = 15
),
pagingSourceFactory = {
storyDao.getByUserId(userId)
}
).flow
}
override fun getStoryById(id: Int): Flow<Story?> = storyDao.getById(id)

View File

@ -1,12 +1,14 @@
package com.example.mobileapp.database.repositories
import androidx.paging.PagingData
import androidx.paging.PagingSource
import com.example.mobileapp.database.entities.Story
import kotlinx.coroutines.flow.Flow
interface StoryRepository {
fun getAllStories(): Flow<List<Story>>
fun getAllStories(): Flow<PagingData<Story>>
fun getStoriesByUserId(userId: Int): Flow<List<Story>>
fun getStoriesByUserId(userId: Int): Flow<PagingData<Story>>
fun getStoryById(id: Int): Flow<Story?>

View File

@ -2,13 +2,15 @@ package com.example.mobileapp.database.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.mobileapp.database.entities.Mail
import com.example.mobileapp.database.repositories.MailRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
class MailViewModel(private val mailRepository: MailRepository): ViewModel() {
val getAllMails = mailRepository.getAllMails()
val getAllMails: Flow<PagingData<Mail>> = mailRepository.getAllMails().cachedIn(viewModelScope)
fun getMail(id: Int): Flow<Mail?> = mailRepository.getMail(id)

View File

@ -2,6 +2,8 @@ package com.example.mobileapp.database.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.mobileapp.database.entities.Story
import com.example.mobileapp.database.repositories.StoryRepository
import kotlinx.coroutines.flow.Flow
@ -9,11 +11,11 @@ import kotlinx.coroutines.launch
class StoryViewModel(private val storyRepository: StoryRepository): ViewModel() {
val getAllStories = storyRepository.getAllStories()
val getAllStories: Flow<PagingData<Story>> = storyRepository.getAllStories().cachedIn(viewModelScope)
fun getStoryById(id: Int): Flow<Story?> = storyRepository.getStoryById(id)
fun getStoriesByUserId(userId: Int): Flow<List<Story>> = storyRepository.getStoriesByUserId(userId)
fun getStoriesByUserId(userId: Int): Flow<PagingData<Story>> = storyRepository.getStoriesByUserId(userId).cachedIn(viewModelScope)
fun insertStory(story: Story) = viewModelScope.launch {
storyRepository.insertStory(story)

View File

@ -67,14 +67,16 @@ fun Authorization(navController: NavHostController,
})
ActiveButton(label = "Вход", backgroundColor = ButtonColor2,
textColor = Color.White, onClickAction = {
userViewModel.authUser(
User(
login = login.value,
password = password.value,
email = String()
if (login.value.isNotEmpty() && password.value.isNotEmpty()) {
userViewModel.authUser(
User(
login = login.value,
password = password.value,
email = String()
)
)
)
navController.navigate("main")
navController.navigate("main")
}
})
NavigationButton(navController = navController, destination = "registration", label = "Регистрация",
backgroundColor = ButtonColor1, textColor = Color.Black)

View File

@ -6,17 +6,18 @@ import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@ -24,6 +25,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
@ -37,7 +39,6 @@ import com.example.mobileapp.R
import com.example.mobileapp.components.ActiveButton
import com.example.mobileapp.components.NavigationButton
import com.example.mobileapp.components.PlaceholderInputField
import com.example.mobileapp.database.MobileAppDataBase
import com.example.mobileapp.database.entities.Mail
import com.example.mobileapp.database.entities.Story
import com.example.mobileapp.database.entities.User
@ -47,9 +48,6 @@ import com.example.mobileapp.database.viewmodels.StoryViewModel
import com.example.mobileapp.database.viewmodels.UserViewModel
import com.example.mobileapp.ui.theme.ButtonColor1
import com.example.mobileapp.ui.theme.ButtonColor2
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.withContext
@Composable
fun EditStoryScreen(navController: NavHostController, storyId: Int? = null,
@ -185,7 +183,7 @@ fun EditUserScreen(navController: NavHostController,
)) {
val context = LocalContext.current
var userId: Int? = null
var userId = remember { mutableStateOf(0) }
val photo = remember { mutableStateOf<Bitmap>(BitmapFactory.decodeResource(context.resources, R.drawable.photoplaceholder)) }
val login = remember { mutableStateOf("") }
val password = remember { mutableStateOf("") }
@ -200,7 +198,6 @@ fun EditUserScreen(navController: NavHostController,
if (Build.VERSION.SDK_INT < 28) {
photo.value = MediaStore.Images
.Media.getBitmap(context.contentResolver, imageData.value)
} else {
val source = ImageDecoder
.createSource(context.contentResolver, imageData.value!!)
@ -208,13 +205,15 @@ fun EditUserScreen(navController: NavHostController,
}
}
GlobalUser.getInstance().getUser()?.let{user ->
if (user!!.photo != null)
photo.value = user!!.photo!!
userId = user!!.id!!
login.value = user!!.login
password.value = user!!.password
email.value = user!!.email
LaunchedEffect(Unit) {
GlobalUser.getInstance().getUser()?.let { user ->
if (user!!.photo != null)
photo.value = user!!.photo!!
userId.value = user!!.id!!
login.value = user!!.login
password.value = user!!.password
email.value = user!!.email
}
}
Column(
@ -228,8 +227,13 @@ fun EditUserScreen(navController: NavHostController,
contentDescription = "editplaceholder",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(384.dp)
.padding(8.dp)
.clip(CircleShape)
.size(384.dp)
.border(
width = 2.dp,
color = MaterialTheme.colorScheme.onPrimary,
)
.align(Alignment.CenterHorizontally))
ActiveButton(label = "Выбрать фото", backgroundColor = ButtonColor1, textColor = Color.Black, onClickAction = {
launcher.launch("image/*")
@ -249,7 +253,7 @@ fun EditUserScreen(navController: NavHostController,
ActiveButton(label = "Сохранить", backgroundColor = ButtonColor1, textColor = Color.Black, onClickAction = {
userViewModel.updateUser(
User(
id = userId,
id = userId.value,
login = login.value,
password = password.value,
email = email.value,
@ -258,7 +262,9 @@ fun EditUserScreen(navController: NavHostController,
)
navController.navigate("settings")
})
NavigationButton(navController = navController, destination = "settings", label = "Назад",
backgroundColor = ButtonColor2, textColor = Color.White)
ActiveButton(label = "Назад", backgroundColor = ButtonColor2, textColor = Color.White,
onClickAction = {
navController.navigate("settings")
})
}
}

View File

@ -3,6 +3,8 @@ package com.example.mobileapp.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
@ -12,9 +14,15 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.mobileapp.components.DataListScroll
import com.example.mobileapp.components.MailListItem
import com.example.mobileapp.components.StoryListItem
import com.example.mobileapp.components.addNewListItem
import com.example.mobileapp.database.MobileAppDataBase
import com.example.mobileapp.database.entities.Mail
import com.example.mobileapp.database.entities.Story
import com.example.mobileapp.database.viewmodels.MailViewModel
import com.example.mobileapp.database.viewmodels.MobileAppViewModelProvider
import com.example.mobileapp.ui.theme.BackgroundItem1
@ -27,13 +35,29 @@ fun ListMailScreen(navController: NavHostController,
mailViewModel: MailViewModel = viewModel(
factory = MobileAppViewModelProvider.Factory
)) {
val mails = mailViewModel.getAllMails.collectAsState(emptyList()).value
val mails = mailViewModel.getAllMails.collectAsLazyPagingItems()
Column(
modifier = Modifier
.fillMaxSize()
.background(BackgroundItem1)
) {
DataListScroll(navController, mails)
LazyVerticalGrid(
columns = GridCells.Fixed(1)
) {
item {
addNewListItem(navController, "editmail")
}
items(
count = mails.itemCount,
key = mails.itemKey { item -> item.id!! }
) { index: Int ->
val mail: Mail? = mails[index]
if (mail != null) {
MailListItem(item = mail)
}
}
}
//DataListScroll(navController, mails)
}
}

View File

@ -3,38 +3,53 @@ package com.example.mobileapp.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.mobileapp.GlobalUser
import com.example.mobileapp.components.DataListScroll
import com.example.mobileapp.database.MobileAppDataBase
import com.example.mobileapp.components.StoryListItem
import com.example.mobileapp.components.addNewListItem
import com.example.mobileapp.database.entities.Story
import com.example.mobileapp.database.viewmodels.MobileAppViewModelProvider
import com.example.mobileapp.database.viewmodels.StoryViewModel
import com.example.mobileapp.ui.theme.BackgroundItem1
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
fun ListStoryScreen(navController: NavHostController,
storyViewModel: StoryViewModel = viewModel(
factory = MobileAppViewModelProvider.Factory
)) {
//val stories = storyViewModel.getStoriesByUserId(GlobalUser.getInstance().getUser()?.id!!).collectAsState(emptyList()).value
val stories = storyViewModel.getAllStories.collectAsState(emptyList()).value
val stories = storyViewModel.getStoriesByUserId(GlobalUser.getInstance().getUser()?.id!!).collectAsLazyPagingItems()
//val stories = storyViewModel.getAllStories.collectAsLazyPagingItems()
Column(
modifier = Modifier
.fillMaxSize()
.background(BackgroundItem1)
) {
DataListScroll(navController, stories)
LazyVerticalGrid(
columns = GridCells.Fixed(1)
) {
item {
addNewListItem(navController, "editstory")
}
items(
count = stories.itemCount,
key = stories.itemKey { item -> item.id!! }
) { index: Int ->
val story: Story? = stories[index]
if (story != null) {
StoryListItem(item = story, navController = navController)
}
}
}
//DataListScroll(navController, stories)
}
}

View File

@ -8,6 +8,8 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
@ -18,38 +20,64 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.mobileapp.R
import com.example.mobileapp.components.NavBar
import com.example.mobileapp.components.SearchInputField
import com.example.mobileapp.components.StoryListItem
import com.example.mobileapp.components.addNewListItem
import com.example.mobileapp.database.entities.Story
import com.example.mobileapp.database.viewmodels.MobileAppViewModelProvider
import com.example.mobileapp.database.viewmodels.StoryViewModel
@Composable
fun MainScreen(navController: NavHostController) {
fun MainScreen(navController: NavHostController,
storyViewModel: StoryViewModel = viewModel(
factory = MobileAppViewModelProvider.Factory
)) {
val stories = storyViewModel.getAllStories.collectAsLazyPagingItems()
Column(
modifier = Modifier
.fillMaxSize()
) {
SearchInputField()
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.89f),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.main),
contentDescription = "main",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(512.dp)
.padding(8.dp)
)
Text(
text = "Здесь будут посты авторов",
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
if (stories.itemCount > 0){
LazyVerticalGrid(
columns = GridCells.Fixed(1)
) {
items(
count = stories.itemCount,
key = stories.itemKey { item -> item.id!! }
) { index: Int ->
val story: Story? = stories[index]
if (story != null) {
StoryListItem(item = story, navController = navController, isReadOnly = true)
}
}
}
}
else {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.main),
contentDescription = "main",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(512.dp)
.padding(8.dp)
)
Text(
text = "Здесь будут посты авторов",
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}