我正在尝试启动并运行 Android 开发和 Room。
我正在制作一个带有播放列表和文件浏览器的音乐播放器应用程序,该应用程序能够将轨道添加到当前播放列表。
我正在将播放列表保存在 Room 数据库中。
我从第一次运行程序就遇到问题,数据库中没有任何数据。
我想在数据库中查询最后打开的播放列表,但如果数据库中没有播放列表,我想创建一个空的 PlayList 对象。
7 public class PlayListRepository
8 {
9 public PlayListRepository(Application application)
10 {
11 _application = application;
12 }
13
14 public LiveData<PlayListWithTracks> getPlayList(int playListId)
15 {
16 if (_appDao == null) {
17 InitDb();
18 }
19 LiveData<PlayListWithTracks> livePlayListWithTracks = _appDao.getByIdWithTracks(playListId);
20 if (livePlayListWithTracks.getValue() == null) {
21 livePlayListWithTracks.setValue(new PlayListWithTracks());
22 }
23 return livePlayListWithTracks;
24 }
25
26
27 private void InitDb()
28 {
29 AppDatabase db = AppDatabase.getDatabase(_application);
30 _appDao = db.appDao();
31 }
32
33 private Application _application;
34 private AppDao _appDao;
35 }
第 21 行无法编译。它说error: setValue(T) has protected access in LiveData
.
我的AppDao.getByIdWithTracks
方法如下:
@Dao
public interface AppDao
{
@Transaction
@Query("SELECT * FROM PlayList WHERE Id = :id")
LiveData<PlayListWithTracks> getByIdWithTracks(int id);
}
我尝试过转换 livePlayListWithTracks
至MutableLiveData<PlayListWithTracks>
,但这给了我一个运行时错误 androidx.room.RoomTrackingLiveData cannot be cast to androidx.lifecycle.MutableLiveData
我尝试将其转换为 RoomTrackingLiveData
,但 Android Studio 无法识别 androidx.room
导入。
我是不是走错了路还是什么?
编辑:这是 PlayListWithTracks:
public class PlayListWithTracks
{
@Embedded
public PlayList playList;
@Relation(
parentColumn = "id",
entityColumn = "playListId"
)
public List<Track> tracks = new Vector<Track>();
}
最佳答案
LiveData
表示数据库中的数据。如果您从应用程序的任何其他部分修改数据库中的该条目,您的 LiveData
将反射(reflect)该更改。尝试为 LiveData
设置另一个值没有任何意义。
如果您不需要观察数据的变化,那么您可以返回数据访问对象中的对象。就像这样:
@Dao
public interface AppDao
{
@Transaction
@Query("SELECT * FROM PlayList WHERE Id = :id")
PlayListWithTracks getByIdWithTracks(int id);
}
也许更好的方法是在数据库中创建一个新的播放列表条目(如果该条目不存在),然后访问该条目。这意味着您可以使用函数中收到的 id
将新的 PlayListWithTracks
实体添加到数据库,然后访问该实体
关于java - 安卓房间: error: setValue(T) has protected access in LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63970736/