Activity 如何在没有 RecyclerView 的情况下填充 Room 数据库
How to populate Room database without RecyclerView in Activity
我想在 onCreate 方法中首先打开 Activity 时填充 Room 数据库。我正在关注他们使用 RecyclerView 的教程。但是一开始我只是不需要在RecyclerView中看到数据。
如何在不使用 RecyclerView 的情况下填充数据库。
RestaurantRepository.kt
class RestaurantRepository @Inject constructor(
private val api: RestaurantApi,
private val db: SybaseDatabase
) {
private val restaurantDao = db.restaurantDao()
fun getRestaurants() = networkBoundResource(
query = {
restaurantDao.getAllRestaurants()
},
fetch = {
delay(2000)
api.getRestaurants()
},
saveFetchResult = { restaurants ->
db.withTransaction {
restaurantDao.deleteAllRestaurants()
restaurantDao.insertRestaurants(restaurants)
}
}
)
}
RestaurantViewModel.kt
@HiltViewModel
class RestaurantViewModel @Inject constructor(
repository: RestaurantRepository
):ViewModel() {
val restaurants = repository.getRestaurants().asLiveData()
和RestaurantActivity.kt
@AndroidEntryPoint
class RestaurantActivity : AppCompatActivity() {
private val viewModel: RestaurantViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityRestaurantBinding.inflate(layoutInflater)
setContentView(binding.root)
val restaurantAdapter = RestaurantAdapter()
binding.apply {
recyclerView.apply {
adapter = restaurantAdapter
layoutManager = LinearLayoutManager(this@RestaurantActivity)
}
viewModel.restaurants.observe(this@RestaurantActivity) { result ->
restaurantAdapter.submitList(result.data)
progressBar.isVisible = result is Resource.Loading && result.data.isNullOrEmpty()
textViewErrorr.isVisible = result is Resource.Error && result.data.isNullOrEmpty()
textViewErrorr.text = result.error?.localizedMessage
}
}
}
}
编辑:
Dao.kt
Import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface SybaseDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRestaurants(restaurant: List<Restaurant>)
@Query("DELETE FROM restaurants")
suspend fun deleteAllRestaurants()
@Query("SELECT * FROM restaurants")
fun getAllRestaurants(): Flow<List<Restaurant>>
这是模特class
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "restaurants")
data class Restaurant (
@PrimaryKey val name: String,
val type: String,
val logo: String,
val address: String
)
其实我有更多型号 classes 但它们看起来很相似。我想要的是首先填充数据库,然后 Activity 我想将数据接收到 RecyclerView。我将拥有三个具有不同 RecyclerView 的活动,当用户选择该项目时,新的 activity 将使用来自不同 table.
的数据启动
如果您只是不想从 activity 中的数据库加载数据,您可以更改观察者代码。
这是您的观察者代码。
viewModel.restaurants.observe(this@RestaurantActivity) { result ->
restaurantAdapter.submitList(result.data)
progressBar.isVisible = result is Resource.Loading && result.data.isNullOrEmpty()
textViewErrorr.isVisible = result is Resource.Error && result.data.isNullOrEmpty()
textViewErrorr.text = result.error?.localizedMessage
}
这一行负责将数据加载到您的 RecyclerView 适配器中。如果省略此行,您的情况下将有一个空的 activity。
restaurantAdapter.submitList(result.data)
请记住,result
包含数据库中的数据,在本例中为列表。事实上,如果您不必使用 activity.
中的数据,您应该删除观察者代码
因为您还想在第一个 activity 的 onCreate 中填充您的数据库。您将需要要插入数据库的列表(比如所有餐厅)数据。您必须在视图模型和存储库中创建方法,将数据插入数据库。
您将像这样调用视图模型的方法:
viewModel.insertAllRestaurants(allRestaurants)
在您的视图模型中,您必须调用存储库的方法来插入数据。
fun insertAllRestaurants(allRestaurants:List<Restaurant>)
{
repository.insertAllRestaurants(allRestaurants)
}
在您的存储库中,您将必须调用您的 insertRestaurants(restaurant: List<Restaurant>)
。
我想在 onCreate 方法中首先打开 Activity 时填充 Room 数据库。我正在关注他们使用 RecyclerView 的教程。但是一开始我只是不需要在RecyclerView中看到数据。 如何在不使用 RecyclerView 的情况下填充数据库。
RestaurantRepository.kt
class RestaurantRepository @Inject constructor(
private val api: RestaurantApi,
private val db: SybaseDatabase
) {
private val restaurantDao = db.restaurantDao()
fun getRestaurants() = networkBoundResource(
query = {
restaurantDao.getAllRestaurants()
},
fetch = {
delay(2000)
api.getRestaurants()
},
saveFetchResult = { restaurants ->
db.withTransaction {
restaurantDao.deleteAllRestaurants()
restaurantDao.insertRestaurants(restaurants)
}
}
)
}
RestaurantViewModel.kt
@HiltViewModel
class RestaurantViewModel @Inject constructor(
repository: RestaurantRepository
):ViewModel() {
val restaurants = repository.getRestaurants().asLiveData()
和RestaurantActivity.kt
@AndroidEntryPoint
class RestaurantActivity : AppCompatActivity() {
private val viewModel: RestaurantViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityRestaurantBinding.inflate(layoutInflater)
setContentView(binding.root)
val restaurantAdapter = RestaurantAdapter()
binding.apply {
recyclerView.apply {
adapter = restaurantAdapter
layoutManager = LinearLayoutManager(this@RestaurantActivity)
}
viewModel.restaurants.observe(this@RestaurantActivity) { result ->
restaurantAdapter.submitList(result.data)
progressBar.isVisible = result is Resource.Loading && result.data.isNullOrEmpty()
textViewErrorr.isVisible = result is Resource.Error && result.data.isNullOrEmpty()
textViewErrorr.text = result.error?.localizedMessage
}
}
}
}
编辑: Dao.kt
Import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface SybaseDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRestaurants(restaurant: List<Restaurant>)
@Query("DELETE FROM restaurants")
suspend fun deleteAllRestaurants()
@Query("SELECT * FROM restaurants")
fun getAllRestaurants(): Flow<List<Restaurant>>
这是模特class
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "restaurants")
data class Restaurant (
@PrimaryKey val name: String,
val type: String,
val logo: String,
val address: String
)
其实我有更多型号 classes 但它们看起来很相似。我想要的是首先填充数据库,然后 Activity 我想将数据接收到 RecyclerView。我将拥有三个具有不同 RecyclerView 的活动,当用户选择该项目时,新的 activity 将使用来自不同 table.
的数据启动如果您只是不想从 activity 中的数据库加载数据,您可以更改观察者代码。
这是您的观察者代码。
viewModel.restaurants.observe(this@RestaurantActivity) { result ->
restaurantAdapter.submitList(result.data)
progressBar.isVisible = result is Resource.Loading && result.data.isNullOrEmpty()
textViewErrorr.isVisible = result is Resource.Error && result.data.isNullOrEmpty()
textViewErrorr.text = result.error?.localizedMessage
}
这一行负责将数据加载到您的 RecyclerView 适配器中。如果省略此行,您的情况下将有一个空的 activity。
restaurantAdapter.submitList(result.data)
请记住,result
包含数据库中的数据,在本例中为列表。事实上,如果您不必使用 activity.
因为您还想在第一个 activity 的 onCreate 中填充您的数据库。您将需要要插入数据库的列表(比如所有餐厅)数据。您必须在视图模型和存储库中创建方法,将数据插入数据库。
您将像这样调用视图模型的方法:
viewModel.insertAllRestaurants(allRestaurants)
在您的视图模型中,您必须调用存储库的方法来插入数据。
fun insertAllRestaurants(allRestaurants:List<Restaurant>)
{
repository.insertAllRestaurants(allRestaurants)
}
在您的存储库中,您将必须调用您的 insertRestaurants(restaurant: List<Restaurant>)
。