如何在 Jetpack Compose 的 LazyColumn 中显示我们的房间数据库内容?

问题描述 投票:0回答:2

到现在为止,我已经快10天了,我在YouTube上搜索和观看视频来寻找答案,但我找不到它。如果可以的话请帮助我。

这里开始我的 MainActivity 代码:

    class MainActivity : ComponentActivity() {

lateinit var appDB: AppDatabase

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MyVolleyTheme {

            appDB = AppDatabase.getDatabase(this)

                Surface(
                    modifier = Modifier
                        .fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {

                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier
                    ) {

                        Spacer(modifier = Modifier.height(30.dp))

                        val text1 = remember { mutableStateOf("") }
                        TextField(
                            modifier = Modifier
                                .height(60.dp)
                                .fillMaxWidth()
                                .padding(0.dp),
                            value = text1.value,
                            onValueChange = { nextText ->
                                text1.value = nextText
                            },
                            label = {
                                Text(
                                    modifier = Modifier.padding(0.dp),
                                    text = "LastName",
                                    textAlign = TextAlign.Center,
                                    fontSize = 13.sp
                                )
                            },
                            singleLine = true,
                            trailingIcon = {
                                IconButton(onClick = {

                                }) {
                                    Icon(
                                        imageVector = Icons.Filled.Face,
                                        contentDescription = "lastName",
                                        modifier = Modifier.size(25.dp)
                                    )
                                }
                            },
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Text,
                                imeAction = ImeAction.Next
                            ),
                        )

                        val text2 = remember { mutableStateOf("") }
                        TextField(
                            modifier = Modifier
                                .height(60.dp)
                                .fillMaxWidth()
                                .padding(0.dp),
                            value = text2.value,
                            onValueChange = { nextText ->
                                text2.value = nextText
                            },
                            label = {
                                Text(
                                    modifier = Modifier.padding(0.dp),
                                    text = "Age",
                                    textAlign = TextAlign.Center,
                                    fontSize = 13.sp
                                )
                            },
                            singleLine = true,
                            trailingIcon = {
                                IconButton(onClick = {

                                }) {
                                    Icon(
                                        imageVector = Icons.Filled.Person,
                                        contentDescription = "Age",
                                        modifier = Modifier.size(25.dp)
                                    )
                                }
                            },
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Number,
                                imeAction = ImeAction.Done
                            ),
                        )

                        Button(onClick = {
                            if (text1.value.isNotEmpty() && text2.value.isNotEmpty()) {

                                val example = User(null, text1.value, text2.value.toInt())
                                lifecycleScope.launch(Dispatchers.IO) {
                                    appDB.userDao().insertAll(example)
                                }
                                Toast.makeText(
                                    this@MainActivity,
                                    "Data inserted successfully",
                                    Toast.LENGTH_LONG
                                ).show()
                                text1.value = ""
                                text2.value = ""

                            } else if (text1.value.isEmpty() || text2.value
                                    .isEmpty()
                            ) {
                                Toast.makeText(
                                    this@MainActivity,
                                    "Please fill the fields",
                                    Toast.LENGTH_LONG
                                ).show()
                            }
                        }) {
                            Text(text = "Save is database")
                        }

                        Spacer(modifier = Modifier.height(60.dp))


                        **// Showing a LazyColumn of our Database Content Here**


                    }
                }
            }
        }
    }
}
    

我的房间实体代码是:

    @Entity(tableName = "user_table")
data class User(
@PrimaryKey(autoGenerate = true) val uid: Int?,
@ColumnInfo(name = "last_name") val lastName: String?,
@ColumnInfo(name = "age") val age: Int?
 )

还有我的Room Dao:

@Dao
interface UserDao {
@Query("SELECT * FROM user_table")
fun getAll(): List<User>

@Query("SELECT * FROM user_table WHERE uid IN (:userIds)")
suspend fun loadAllByIds(userIds: IntArray): List<User>

@Query(
    "SELECT * FROM user_table WHERE last_name LIKE :last AND " + "age LIKE :age LIMIT 1"
)
suspend fun findByNameAge(last: String, age: Int): User

@Insert
suspend fun insertAll(vararg users: User)

@Delete
suspend fun delete(user: User)
}

还有我的房间数据库:

 @Database(entities = [User::class], version = 1, exportSchema = false)
 abstract class AppDatabase : RoomDatabase() {
 abstract fun userDao(): UserDao

 companion object {
    @Volatile
    private var INSTANCE: AppDatabase? = null

    fun getDatabase(context: Context): AppDatabase {
        val tempInstance = INSTANCE
        if (tempInstance != null) {
            return tempInstance
        }
        synchronized(this) {
            val instance = Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                "user_database"
            ).build()
            INSTANCE = instance
            return instance
        }
    }
}
}

使用这些代码,我可以成功地将数据插入我的 Room 数据库。但如何在 lazycolumn 中显示我的数据库?

android-jetpack-compose android-room android-jetpack lazycolumn
2个回答
3
投票

这是在 LazyColumn 中显示 Room 数据库表的基本代码:

// table:
@Entity(tableName = "word_table")
class Word(
    @PrimaryKey @ColumnInfo(name = "word") val text: String
)

// DAO:
@Query("SELECT * FROM word_table ORDER BY word COLLATE NOCASE ASC")
fun getAlphabetizedWords(): Flow<List<Word>>

@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(word: Word)

// repository:
val allWords: Flow<List<Word>> = wordDao.getAlphabetizedWords()

suspend fun insert(word: Word) {
    wordDao.insert(word)
}

// viewModel:
val allWords: LiveData<List<Word>> = repository.allWords.asLiveData()

fun insert(word: Word) = viewModelScope.launch {
    repository.insert(word)
}

// simplified composable:
@Composable
fun WordList() {
   val list by mWordViewModel.allWords.observeAsState(listOf())

   LazyColumn() {
      items(list) { word ->
         Row() {
            Text(word.text)
         }
      }
   }
}

1
投票

要显示从数据库到 lazyColumn 的所有记录,请从 DAO 类到存储库类调用 getAll() 方法。 在我的应用程序中,我使用了 coroutineScope 来从 DAO 调用方法到 Repository 类。

fun getAllEmployees() {
    coroutineScope.launch(Dispatchers.IO) {
        allEmployees.postValue(employeeDao.getAllEmployees())
    }
}

将 getAllEmployees() 函数添加到 Repository 类后,我从 viewmodel 类访问它,如下所示:

@HiltViewModel
class HomeViewModel @Inject constructor(private val employeeRepository: 
EmployeeRepository) :
ViewModel() {

fun getAllEmployees(){
    employeeRepository.getAllEmployees()
}

现在,从 viewmodel 类调用 getAllEmployees() 到 mainActivity 类,如下所示:

homeViewModel.getAllEmployees()
val lazyListState = rememberLazyListState()
Scaffold(
    topBar = {
        CustomToolbar(title = stringResource(id = R.string.app_name), openDrawer)
    },
    content = {
        val employeeList: List<Employee> by homeViewModel.employeeList.observeAsState(initial = listOf())
        if (employeeList.isNotEmpty()) {
            Surface(color = Color.White, modifier = Modifier.fillMaxSize()) {
                LazyColumn(
                    modifier = Modifier.padding(vertical = 4.dp),
                    state = lazyListState
                ) {
                    items(items = employeeList) { emp ->
                        EmployeeCard(employee = emp, navController = navController)
                    }
                }
            }
        } else {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(20.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Text(
                    "No employees onboarded yet.",
                    fontSize = 20.sp,
                    modifier = Modifier
                        .wrapContentWidth()
                        .wrapContentHeight(),
                    textAlign = TextAlign.Center
                )
            }
        }
    }

在此处查看 Github 演示:https://github.com/MansiKothari15/HRComposeApp。 在这里查看博客https://medium.com/jetpack-composers/jetpack-compose-room-db-b7b23bd6b189

© www.soinside.com 2019 - 2024. All rights reserved.