[英]How to populate Room database without RecyclerView in Activity
I would like to populate Room database when open first Activity in onCreate method.我想在 onCreate 方法中打开第一个 Activity 时填充 Room 数据库。 I am following tutorial where they use RecyclerView.
我正在关注他们使用 RecyclerView 的教程。 But I just don't need to see data in RecyclerView at the beginning.
但我只是不需要一开始就在 RecyclerView 中查看数据。 How can I populate database withou using RecyclerView.
如何在不使用 RecyclerView 的情况下填充数据库。
RestaurantRepository.kt 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 RestaurantViewModel.kt
@HiltViewModel
class RestaurantViewModel @Inject constructor(
repository: RestaurantRepository
):ViewModel() {
val restaurants = repository.getRestaurants().asLiveData()
And RestaurantActivity.kt和 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
}
}
}
}
EDIT: Dao.kt编辑:道.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>>
This is model class这是 model 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
)
Actually I have more model classes but they look similar.实际上我有更多的 model 类,但它们看起来很相似。 What I want is to first populate the database and in other Activity I want to recieve data to RecyclerView.
我想要的是首先填充数据库,然后在其他活动中我想将数据接收到 RecyclerView。 I will have like three activities with different RecyclerViews and when user chose the item then new activity is started with data from different table.
我将拥有三个具有不同 RecyclerViews 的活动,当用户选择该项目时,新活动将使用来自不同表的数据启动。
If you just don't want to load the data from database in your activity, you can change your observer code.如果您只是不想在活动中从数据库加载数据,则可以更改观察者代码。
This is your observer code.这是您的观察者代码。
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
}
This line is responsible for loading the data into your RecyclerView adapter.此行负责将数据加载到您的 RecyclerView 适配器中。 If you omit this line you will have an empty activity in your case.
如果您省略此行,您的案例中将有一个空活动。
restaurantAdapter.submitList(result.data)
Remember, result
cotains the data from your database which is a List in this case.请记住,
result
包含数据库中的数据,在这种情况下是列表。 In fact you should remove the observer code if you don't have to use the data in your activity.事实上,如果您不必在活动中使用数据,则应该删除观察者代码。
Since you further want to populate your database in the onCreate of first activity.由于您还希望在第一个活动的 onCreate 中填充您的数据库。 You will require List(say allRestaurants) data you want to insert in the database.
您将需要列表(比如 allRestaurants)要插入数据库的数据。 You will have to create methods in viewmodel and repository which will insert the data into database.
您必须在视图模型和存储库中创建方法,将数据插入数据库。
You will call the viewmodel's method like:您将调用 viewmodel 的方法,如:
viewModel.insertAllRestaurants(allRestaurants)
Inside your viewmodel, you will have to call repository's method for inserting the data.在您的视图模型中,您必须调用存储库的方法来插入数据。
fun insertAllRestaurants(allRestaurants:List<Restaurant>)
{
repository.insertAllRestaurants(allRestaurants)
}
Inside your repository, you will have to invoke your insertRestaurants(restaurant: List<Restaurant>)
.在您的存储库中,您必须调用您的
insertRestaurants(restaurant: List<Restaurant>)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.