3-ая не работает все еще

This commit is contained in:
Артём Алейкин 2023-12-18 22:09:12 +04:00
parent 0e97bb7444
commit ad397832d9
6 changed files with 97 additions and 102 deletions

View File

@ -11,7 +11,7 @@ android {
defaultConfig { defaultConfig {
applicationId = "com.example.myapplication" applicationId = "com.example.myapplication"
minSdk = 24 minSdk = 24
targetSdk = 33 targetSdk = 34
versionCode = 1 versionCode = 1
versionName = "1.0" versionName = "1.0"
@ -50,6 +50,7 @@ android {
} }
} }
dependencies { dependencies {
implementation("androidx.core:core-ktx:1.9.0") implementation("androidx.core:core-ktx:1.9.0")

View File

@ -1,14 +1,13 @@
import android.content.Context import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable import android.util.Log
import androidx.room.Database import androidx.room.Database
import androidx.room.Room import androidx.room.Room
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import androidx.room.TypeConverters import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.myapplication.R import com.example.myapplication.R
import com.example.myapplication.database.ImageConverter import com.example.myapplication.database.entities.ImageConverter
import com.example.myapplication.database.dao.CardDao import com.example.myapplication.database.dao.CardDao
import com.example.myapplication.database.dao.UserDao import com.example.myapplication.database.dao.UserDao
import com.example.myapplication.database.entities.Card import com.example.myapplication.database.entities.Card
@ -29,30 +28,17 @@ abstract class MobileAppDataBase : RoomDatabase() {
@Volatile @Volatile
private var INSTANCE: MobileAppDataBase? = null private var INSTANCE: MobileAppDataBase? = null
suspend fun initialDataBase(appContext: Context){
INSTANCE?.let { database ->
val userDao = database.userDao()
userDao.insert(User(id = 1, login = "Иван", password = "1234",))
userDao.insert(User(id = 2, login = "Леонель Месси", password = "4321",))
val cardDao = database.cardDao()
cardDao.insert(Card(name = "Феррари Имба", location = "г. Ульяновск",
image = BitmapFactory.decodeResource(appContext.resources, R.drawable.ferrari_laferrari_car2), mileage = 7322, price = 125000, userId = 1)
)
cardDao.insert(Card(name = "Москоувич", location = "г. Москва",
image = BitmapFactory.decodeResource(appContext.resources, R.drawable.moscowich_car3), mileage = 156771, price = 1000, userId = 1)
)
}
}
fun getInstance(appContext: Context): MobileAppDataBase { fun getInstance(appContext: Context): MobileAppDataBase {
return INSTANCE ?: synchronized(this) { return INSTANCE ?: synchronized(this) {
Room.databaseBuilder( INSTANCE?.let { return@let it } // Возвращаем INSTANCE, если он уже был создан
val instance = Room.databaseBuilder(
appContext, appContext,
MobileAppDataBase::class.java, MobileAppDataBase::class.java,
DB_NAME DB_NAME
) )
.addCallback(object : Callback() { .fallbackToDestructiveMigration()
.addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) { override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db) super.onCreate(db)
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
@ -60,9 +46,48 @@ abstract class MobileAppDataBase : RoomDatabase() {
} }
} }
}) })
.fallbackToDestructiveMigration() .also { INSTANCE = it.build() } // Сохраняем INSTANCE
.build() .build()
.also { INSTANCE = it }
Log.d("Database", "Database instance created")
instance // Возвращаем созданный instance
}
}
private suspend fun initialDataBase(appContext: Context) {
INSTANCE?.let { database ->
val userDao = database.userDao()
userDao.insert(User(id = 1, login = "Иван", password = "1234",))
userDao.insert(User(id = 2, login = "Леонель Месси", password = "4321",))
val cardDao = database.cardDao()
cardDao.insert(
Card(
name = "Феррари Имба",
location = "г. Ульяновск",
image = BitmapFactory.decodeResource(
appContext.resources,
R.drawable.ferrari_laferrari_car2
),
mileage = 7322,
price = 125000,
userId = 1
)
)
cardDao.insert(
Card(
name = "Москоувич",
location = "г. Москва",
image = BitmapFactory.decodeResource(
appContext.resources,
R.drawable.moscowich_car3
),
mileage = 156771,
price = 1000,
userId = 1
)
)
} }
} }
} }

View File

@ -5,8 +5,6 @@ import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.ForeignKey import androidx.room.ForeignKey
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.example.myapplication.database.ImageConverter
@Entity( @Entity(
tableName = "cards", tableName = "cards",

View File

@ -1,4 +1,4 @@
package com.example.myapplication.database package com.example.myapplication.database.entities
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory

View File

@ -1,5 +1,6 @@
package com.example.myapplication.screens package com.example.myapplication.screens
import android.util.Log
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@ -42,10 +43,15 @@ fun Authorization(navController: NavHostController){
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
MobileAppDataBase.getInstance(context).userDao().getAll().collect { data -> try {
val database = MobileAppDataBase.getInstance(context.applicationContext)
database.userDao().getAll().collect { data ->
users.clear() users.clear()
users.addAll(data) users.addAll(data)
} }
} catch (e: Exception) {
Log.e("DatabaseError", "Error accessing database", e)
}
} }
} }

View File

@ -1,5 +1,6 @@
package com.example.myapplication.screens package com.example.myapplication.screens
import android.util.Log
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border import androidx.compose.foundation.border
@ -25,8 +26,10 @@ import com.example.myapplication.database.entities.Card
import com.example.myapplication.ui.theme.SkyBlue import com.example.myapplication.ui.theme.SkyBlue
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
@ -40,11 +43,14 @@ import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text import androidx.compose.material3.Text
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 com.example.myapplication.R import com.example.myapplication.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@Composable @Composable
@ -54,81 +60,40 @@ fun MainScreen(navController: NavHostController) {
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
MobileAppDataBase.getInstance(context).cardDao().getAll().collect { data -> try {
val database = MobileAppDataBase.getInstance(context.applicationContext)
database.cardDao().getAll().collect { data ->
cards.clear() cards.clear()
cards.addAll(data) cards.addAll(data)
} }
} catch (e: Exception) {
Log.e("DatabaseError", "Error accessing database", e)
}
} }
} }
Box() {
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.background(Color.White) .background(Color.White)
.fillMaxHeight(0.9f)
) { ) {
DataListScroll(navController, cards) DataListScroll(navController, cards)
} }
}
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.background(SkyBlue), .background(SkyBlue)
.fillMaxHeight(0.1f),
verticalArrangement = Arrangement.Center verticalArrangement = Arrangement.Center
) { ) {
navBar(navController = navController) navBar(navController = navController)
} }
} }
/*@Composable
private fun ListItem(
card: Card,
navController: NavHostController
) {
val bitmap = remember(card) {
BitmapFactory.decodeByteArray(card.image, 0, card.image.size)
}
val imageBitmap = remember(bitmap) {
bitmap.asImageBitmap()
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.border(2.dp, Color.Gray, RoundedCornerShape(15.dp)),
shape = RoundedCornerShape(15.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 5.dp),
) {
Box {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
painter = remember {
BitmapPainter(imageBitmap)
},
contentDescription = "image",
contentScale = ContentScale.Crop,
modifier = Modifier.size(128.dp)
)
Column(
modifier = Modifier.padding(5.dp)
) {
Text(text = card.name, fontWeight = FontWeight.Bold)
Text(text = "Пробег: ${card.mileage}")
Text(text = "Расположение: ${card.location}")
Text(text = "Цена: ${card.price}")
Button(onClick = { navController.navigate("editCard") }) {
Text("Изменить")
}
Button(onClick = { }) {
Text("Удалить")
}
}
}
}
}
}*/
@Composable @Composable
fun <T : Any> DataListScroll(navController: NavHostController, dataList: List<T>){ fun <T : Any> DataListScroll(navController: NavHostController, dataList: List<T>){
LazyColumn( LazyColumn(