Android房间:错误:setValue(T)在LiveData中具有受保护的访问权限



我正在尝试使用Android开发和Room。

我正在制作一个带有播放列表和文件浏览器的音乐播放器应用程序,可以将曲目添加到当前播放列表中。

我正在将播放列表保存在Room数据库中。

我从第一次运行程序时就遇到了问题,而且数据库中没有任何数据。

我想查询数据库中最后打开的播放列表,但如果数据库中没有播放列表,我想创建一个空的播放列表对象。

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导入。

我是不是走错了路?

编辑:这是带有曲目的播放列表:

public class PlayListWithTracks
{
@Embedded
public PlayList playList;
@Relation(
parentColumn = "id",
entityColumn = "playListId"
)
public List<Track> tracks = new Vector<Track>();
}

LiveData表示数据库中的数据。如果您从应用程序的任何其他部分修改数据库中的该条目,则LiveData将反映该更改。尝试为LiveData设置另一个值没有任何作用。

如果您不需要观察数据中的更改,那么您可能可以在数据访问对象中返回该对象。像这样:

@Dao
public interface AppDao
{
@Transaction
@Query("SELECT * FROM PlayList WHERE Id = :id")
PlayListWithTracks getByIdWithTracks(int id);
}

也许更好的方法是在数据库中创建一个新的播放列表条目,如果它不存在,然后访问该条目。这意味着您可以使用函数中接收到的id将新的PlayListWithTracks实体添加到数据库中,然后访问该实体

最新更新