我只是在房间数据库中有一行,但是当我读取它时,我得到两行一个值。我不知道这是如何房间数据库工作或我错过了一些东西。
我希望每个人都有一个美好的一天!FriendModel
@Entity(tableName = "friend_table")
class FriendModel
: Serializable {
@PrimaryKey
@NonNull
var _id: String = ""
...
}
DAO接口
@Dao
interface FriendDAO {
...
@Query("select _id from friend_table")
fun readRoomIdFriendsDAO() : LiveData<List<String>>
}
库
class UserRepository(private val userAPI: UserAPI, context : Context) {
private val userDAO : UserDAO
private val friendDAO : FriendDAO
init {
val userDatabase: UserRoomDatabase = UserRoomDatabase.getInstance(context)
val friendDatabase: FriendRoomDatabase = FriendRoomDatabase.getInstance(context)
userDAO = userDatabase.getUserDao()
friendDAO = friendDatabase.getFriendDao()
}
...
fun readRoomIdFriendsDAO() : LiveData<List<String>> = friendDAO.readRoomIdFriendsDAO()
}
视图模型
class UserViewModel(private val userRepository: UserRepository) : ViewModel() {
...
fun readRoomIdFriendsDAO() : LiveData<List<String>> = userRepository.readRoomIdFriendsDAO()
}
和我使用它在MainActivity
viewModel.readRoomIdFriendsDAO().observe(this,{ listRoomId ->
if(listRoomId!=null && listRoomId.isNotEmpty()){
for(item in listRoomId){
Log.e(TAG, "RoomId: $listRoomId")
}
}
})
这是我得到的
E/Log: RoomId: [IZnIP4srwDZiB1foauiZF6R60RF3]
...
E/Log: RoomId: [IZnIP4srwDZiB1foauiZF6R60RF3]
可能你叫了两次readRoomIdFriendsDAO()
。Android源代码没有错