ОНО РАБОТАЕТ.

This commit is contained in:
ElEgEv 2023-11-14 10:39:48 +04:00
parent 3e81ac477d
commit ca8ecfa033
18 changed files with 195 additions and 150 deletions

Binary file not shown.

View File

@ -27,7 +27,7 @@ interface NationDao {
//получить нацию без списка танков
@Query(
"SELECT name FROM nations where nations.uid = :uid"
"SELECT nationName FROM nations where nations.uid = :uid"
)
open fun getSimpleNationUid(uid: Long): Nation

View File

@ -7,6 +7,8 @@ import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
import ru.ulstu.`is`.pmu.tank.model.Tank
import ru.ulstu.`is`.pmu.tank.model.TankWithNationAndLevel
import ru.ulstu.`is`.pmu.tank.model.User
import ru.ulstu.`is`.pmu.tank.model.UserTankCrossRef
import ru.ulstu.`is`.pmu.tank.model.UserWithTanks
@ -17,13 +19,20 @@ interface UserDao {
fun getAll(): Flow<List<User>>
//получить нации с танками
@Query("SELECT * FROM users")
/*@Query("SELECT * FROM users")
@Transaction
fun getUsersWithTanks(): List<UserWithTanks>
fun getUsersWithTanks(): Flow<List<TankWithNationAndLevel>>*/
//получить конкретного пользователя
@Query("select * from users where users.userId = :uid")
suspend fun getUserUid(uid: Long): UserWithTanks
@Query(
"SELECT u.*, t.*, l.level, n.nationName FROM users AS u " +
"LEFT JOIN UserTankCrossRef as ut on u.userId = ut.userId " +
"LEFT JOIN tanks as t on ut.tankId = t.tankId " +
"LEFT JOIN levels as l on t.levelId = l.uid " +
"LEFT JOIN nations as n on t.nationId = n.uid " +
"WHERE u.userId = :uid"
)
fun getUserUid(uid: Long): Flow<Map<User, List<TankWithNationAndLevel>>>
@Query("select * from users where users.userId = :uid")
suspend fun getSimpleUserUid(uid: Long): User

View File

@ -29,7 +29,7 @@ abstract class AppDatabase : RoomDatabase() {
abstract fun userDao() : UserDao
companion object {
private const val DB_NAME: String = "seven-db"
private const val DB_NAME: String = "nine-db"
@Volatile
private var INSTANCE: AppDatabase? = null
@ -38,16 +38,16 @@ abstract class AppDatabase : RoomDatabase() {
INSTANCE?.let { database ->
// Nations
val nationDao = database.nationDao()
val nation1 = Nation("СССР")
val nation2 = Nation("Германия")
val nation3 = Nation("США")
val nation4 = Nation("Великобритания")
val nation5 = Nation("Франция")
val nation6 = Nation("Чехословакия")
val nation7 = Nation( "Швеция")
val nation8 = Nation( "Китай")
val nation9 = Nation( "Япония")
val nation10 = Nation("Италия")
val nation1 = Nation(1L, "СССР")
val nation2 = Nation(2L, "Германия")
val nation3 = Nation(3L, "США")
val nation4 = Nation(4L, "Великобритания")
val nation5 = Nation(5L, "Франция")
val nation6 = Nation(6L, "Чехословакия")
val nation7 = Nation( 7L, "Швеция")
val nation8 = Nation( 8L, "Китай")
val nation9 = Nation( 9L, "Япония")
val nation10 = Nation(10L, "Италия")
nationDao.insert(nation1)
nationDao.insert(nation2)
@ -62,16 +62,16 @@ abstract class AppDatabase : RoomDatabase() {
// Levels
val levelDao = database.levelDao()
val level1 = Level(1)
val level2 = Level(2)
val level3 = Level(3)
val level4 = Level(4)
val level5 = Level(5)
val level6 = Level(6)
val level7 = Level(7)
val level8 = Level(8)
val level9 = Level(9)
val level10 = Level(10)
val level1 = Level(11L, 1)
val level2 = Level(12L, 2)
val level3 = Level(13L, 3)
val level4 = Level(14L, 4)
val level5 = Level(15L, 5)
val level6 = Level(16L, 6)
val level7 = Level(17L, 7)
val level8 = Level(18L, 8)
val level9 = Level(19L, 9)
val level10 = Level(20L, 10)
levelDao.insert(level1)
levelDao.insert(level2)
@ -86,17 +86,17 @@ abstract class AppDatabase : RoomDatabase() {
//Tanks
val tankDao = database.tankDao()
val tank1 = Tank("МС-1", 1000, R.drawable.t_34_85, level1, nation1)
val tank2 = Tank("Т-34-85", 960000, R.drawable.t_34_85, level6, nation1)
val tank3 = Tank("ИС-2", 1230000, R.drawable.t_34_85, level7, nation1)
val tank4 = Tank("ИСУ-152", 2350000, R.drawable.t_34_85, level8, nation1)
val tank5 = Tank("Tiger 1", 1430000, R.drawable.tiger_1, level7, nation2)
val tank6 = Tank("Ferdinand", 2500000, R.drawable.tiger_1, level8, nation2)
val tank7 = Tank("Tiger 2", 2500000, R.drawable.tiger_1, level8, nation2)
val tank8 = Tank("Panther", 1350000, R.drawable.tiger_1, level7, nation2)
val tank9 = Tank("M4A2E3", 990000, R.drawable.sherman, level6, nation3)
val tank10 = Tank("Pershing", 1260000, R.drawable.sherman, level8, nation3)
val tank11 = Tank("Hellcat", 940000, R.drawable.sherman, level7, nation3)
val tank1 = Tank(20L,"МС-1", 1000, R.drawable.t_34_85, level1.uid, nation1.uid)
val tank2 = Tank(21L, "Т-34-85", 960000, R.drawable.t_34_85, level6.uid, nation1.uid)
val tank3 = Tank(22L, "ИС-2", 1230000, R.drawable.t_34_85, level7.uid, nation1.uid)
val tank4 = Tank(23L, "ИСУ-152", 2350000, R.drawable.t_34_85, level8.uid, nation1.uid)
val tank5 = Tank(24L, "Tiger 1", 1430000, R.drawable.tiger_1, level7.uid, nation2.uid)
val tank6 = Tank(25L, "Ferdinand", 2500000, R.drawable.tiger_1, level8.uid, nation2.uid)
val tank7 = Tank(26L, "Tiger 2", 2500000, R.drawable.tiger_1, level8.uid, nation2.uid)
val tank8 = Tank(27L, "Panther", 1350000, R.drawable.tiger_1, level7.uid, nation2.uid)
val tank9 = Tank(28L, "M4A2E3", 990000, R.drawable.sherman, level6.uid, nation3.uid)
val tank10 = Tank(29L, "Pershing", 1260000, R.drawable.sherman, level8.uid, nation3.uid)
val tank11 = Tank(30L, "Hellcat", 940000, R.drawable.sherman, level7.uid, nation3.uid)
tankDao.insert(tank1)
tankDao.insert(tank2)

View File

@ -11,8 +11,7 @@ import androidx.room.PrimaryKey
data class Nation(
@PrimaryKey(autoGenerate = true)
val uid: Long?,
@ColumnInfo(name = "name")
val name: String,
val nationName: String,
) {
@Ignore
constructor(

View File

@ -44,11 +44,3 @@ data class Tank(
}
}
fun getTanks(): List<Tank> {
return listOf(
//Tank("T-38-85", 970000, 6, "СССР"),
//Tank("M3 Lee", 140000, 4, "США"),
//Tank("Foch B", 6100000, 10, "Франция")
)
}

View File

@ -0,0 +1,31 @@
package ru.ulstu.`is`.pmu.tank.model
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.PrimaryKey
data class TankWithNationAndLevel (
@PrimaryKey(autoGenerate = true)
val tankId: Long?,
@ColumnInfo(name = "name")
val name: String,
@ColumnInfo(name = "price")
val price: Int,
@ColumnInfo(name="image")
val image: Int,
val level: Int,
val nationName: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as TankWithNationAndLevel
if (tankId != other.tankId) return false
return true
}
override fun hashCode(): Int {
return (tankId ?: -1) as Int
}
}

View File

@ -31,12 +31,12 @@ data class User (
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Tank
if (userId != other.tankId) return false
other as User
if (userId != other.userId) return false
return true
}
override fun hashCode(): Int {
return (userId ?: -1) as Int
return userId.toInt()
}
}

View File

@ -13,7 +13,7 @@ data class UserWithTanks(
entity = Tank::class,
parentColumn = "userId",
entityColumn = "tankId",
associateBy = Junction(UserTankCrossRef::class,)
associateBy = Junction(UserTankCrossRef::class)
)
val tanks: List<Tank>
val tanks: List<TankWithNationAndLevel>
)

View File

@ -52,7 +52,7 @@ fun Constructor(navController: NavController) {
val currentDestination = navBackStackEntry?.destination
val currentScreen = currentDestination?.route?.let { Screen.getItem(it) }
var name by remember { mutableStateOf("") }
var nationName by remember { mutableStateOf("") }
var price by remember { mutableStateOf("") }
//для работы выпадающего списка уровней
@ -61,7 +61,7 @@ fun Constructor(navController: NavController) {
//для работы выпадающего списка наций
var expandedNation by remember { mutableStateOf(false) }
var selectedNation by remember { mutableStateOf(getNations()[0].name) }
var selectedNation by remember { mutableStateOf(getNations()[0].nationName) }
Column(
verticalArrangement = Arrangement.spacedBy(35.dp),
@ -96,9 +96,9 @@ fun Constructor(navController: NavController) {
}
Column {
TextField(
value = name,
value = nationName,
placeholder = { Text(text = "Название", color = CustomDark) },
onValueChange = { name = it },
onValueChange = { nationName = it },
modifier = Modifier
.width(200.dp),
)
@ -174,9 +174,9 @@ fun Constructor(navController: NavController) {
// menu items
getNations().forEach { selectionOption ->
DropdownMenuItem(
text = { Text(selectionOption.name) },
text = { Text(selectionOption.nationName) },
onClick = {
selectedNation = selectionOption.name
selectedNation = selectionOption.nationName
expandedNation = false
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,

View File

@ -40,6 +40,9 @@ import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import ru.ulstu.`is`.pmu.R
import ru.ulstu.`is`.pmu.composeui.navigation.Screen
@ -54,31 +57,33 @@ import ru.ulstu.`is`.pmu.ui.theme.PmudemoTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Hangar(navController: NavController){
fun Hangar(navController: NavController) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val currentScreen = currentDestination?.route?.let { Screen.getItem(it) }
val context = LocalContext.current
val list = remember { mutableStateListOf<UserWithTanks>() }
val (user, setUser) = remember { mutableStateOf<UserWithTanks?>(null) }
val (users, setUsers) = remember { mutableStateOf<UserWithTanks?>(null) }
val nations = remember { mutableStateListOf<Nation>() }
val levels = remember { mutableStateListOf<Level>() }
fun getData(): Flow<UserWithTanks> {
return flow {
AppDatabase.getInstance(context).userDao().getUserUid(100L).collect() { data ->
emit(data.firstNotNullOf {
UserWithTanks(
user = it.key,
tanks = it.value
)
})
}
}
}
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).userDao().getUsersWithTanks().forEach { data ->
list.clear()
list.add(data)
}
Log.d("КОЛИЧЕСТВО", list.size.toString())
setUser(AppDatabase.getInstance(context).userDao().getUserUid(100L))
AppDatabase.getInstance(context).nationDao().getAll().collect { data ->
nations.clear()
nations.addAll(data)
}
AppDatabase.getInstance(context).levelDao().getAll().collect { data ->
levels.clear()
levels.addAll(data)
getData().collect() {
setUsers(it)
}
}
}
@ -86,93 +91,102 @@ fun Hangar(navController: NavController){
Column(
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
val countRows = user?.tanks?.size?.div(2)
val startIndex = 0
//проверяем на то, что не всё поместилось в ряды по 2 элемента
val oneLastElem = user?.tanks?.size?.rem(2)
if(users != null){
val countRows = users.tanks.size / 2
var index = 0
//проверяем на то, что не всё поместилось в ряды по 2 элемента
val oneLastElem = users.tanks.size % 2
var supportCountRow = countRows
var index = 0
for(n in 1 .. (supportCountRow ?: 1)){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(10.dp, 0.dp, 10.dp, 0.dp)
) {
//цикл для заполнения строки карточек
for (m in 0 .. 1){
Column(
modifier = Modifier.background(CustomYellow)
) {
Box(
Modifier
.background(CustomYellow)
.height(260.dp),
)
{
Card(
colors = CardDefaults.cardColors(
containerColor = CustomYellow,
),
modifier = Modifier
.size(width = 170.dp, height = 250.dp)
.padding(10.dp, 0.dp, 10.dp, 0.dp)
) {
Image(
painter = painterResource(id = user?.tanks?.get(index)?.image ?: R.drawable.t_34_85),
contentDescription = stringResource(id = R.string.tanks_main_title),
var supportCountRow = countRows
for (n in 1..(supportCountRow ?: 1)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(10.dp, 0.dp, 10.dp, 0.dp)
) {
//цикл для заполнения строки карточек
for (m in 0..1) {
Column(
modifier = Modifier.background(CustomYellow)
) {
Box(
Modifier
.background(CustomYellow)
.height(260.dp),
)
{
Card(
colors = CardDefaults.cardColors(
containerColor = CustomYellow,
),
modifier = Modifier
.height(130.dp)
)
Text(
text = user?.tanks?.get(index)?.name ?: "" ,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "Нация: " + nations.find{ it.uid == user?.tanks?.get(index)?.nationId }.toString(),
fontSize = 17.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "Уровень: " + levels.find{ it.uid == user?.tanks?.get(index)?.levelId }.toString(),
fontSize = 17.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "Стоимость: " + user?.tanks?.get(index)?.price.toString(),
fontSize = 17.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
.size(width = 170.dp, height = 250.dp)
.padding(10.dp, 0.dp, 10.dp, 0.dp)
) {
Image(
painter = painterResource(
id = users.tanks[index].image
),
contentDescription = stringResource(id = R.string.tanks_main_title),
modifier = Modifier
.height(130.dp)
)
Text(
text = users.tanks[index].name,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "Нация: " + users.tanks[index].nationName,
fontSize = 17.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "Уровень: " + users.tanks[index].level.toString(),
fontSize = 17.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "Стоимость: " + users.tanks[index].price.toString(),
fontSize = 17.sp,
fontWeight = FontWeight.Bold,
color = Color.Black,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
}
}
}
index++
//если надо будет допечатать ещё один элемент
if(n == supportCountRow && oneLastElem != 0){
supportCountRow = oneLastElem
}
index++
//если надо будет допечатать ещё один элемент
if (n == supportCountRow && oneLastElem != 0) {
supportCountRow = oneLastElem
}
}
}
Spacer(Modifier.height(20.dp))
}
}
Spacer(Modifier.height(20.dp))
}
}