我正试着用Android的开发和空间来运行。
我正在制作一个带有播放列表和文件浏览器的音乐播放器应用程序,它可以向当前的播放列表中添加歌曲。
我要把播放列表保存在一个房间数据库里。
我从第一次就遇到了运行程序的问题,而且数据库中没有任何数据。
我想查询数据库中打开的最后一个播放列表,但是如果数据库中没有播放列表,我希望创建一个空的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不识别androidx.room导入。
我是不是走错路了?
编辑:这里是PlayListWithTracks:
public class PlayListWithTracks
{
@Embedded
public PlayList playList;
@Relation(
parentColumn = "id",
entityColumn = "playListId"
)
public List<Track> tracks = new Vector<Track>();
}发布于 2020-09-19 16:36:46
LiveData表示数据库中的数据。如果您从应用程序的任何其他部分修改数据库中的条目,您的LiveData将反映该更改。尝试为LiveData设置另一个值是没有意义的。
如果不需要观察数据中的更改,则可能可以在数据访问对象中返回该对象。就像这样:
@Dao
public interface AppDao
{
@Transaction
@Query("SELECT * FROM PlayList WHERE Id = :id")
PlayListWithTracks getByIdWithTracks(int id);
}也许更好的方法是在数据库中创建一个新的播放列表条目,如果它不存在,然后访问该条目。这意味着您可以向数据库中添加一个新的PlayListWithTracks实体,其中包含函数中接收的id,然后访问该实体。
https://stackoverflow.com/questions/63970736
复制相似问题