【发布时间】:2018-09-26 19:28:23
【问题描述】:
ViewModel、Repository 和 Dao 类在下面提到。
在 Fragment 中实例化 Viewmodel。
playlistVideoViewModel = ViewModelProviders.of(this).get(PlaylistVideoViewModel.class);
playlistVideoViewModel.getAllPlaylistVideos(String.valueOf(currentBucketId)).observe(this, new PlaylistSongObserver());
查看模型类:
public class PlaylistVideoViewModel extends AndroidViewModel {
private MutableLiveData<List<PlaylistSong>> allPlaylistSongs;
private PlaylistVideoRepo playlistVideoRepo;
public PlaylistVideoViewModel(@NonNull Application application) {
super(application);
playlistVideoRepo = new PlaylistVideoRepo(application);
allPlaylistSongs = new MutableLiveData<>();
}
public LiveData<List<PlaylistSong>> getAllPlaylistVideos(String playlistId) {
new GetPlaylistSongs().execute(playlistId);
return allPlaylistSongs;
}
public void delete(String path) {
playlistVideoRepo.delete(path);
}
@SuppressLint("StaticFieldLeak")
class GetPlaylistSongs extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
allPlaylistSongs.postValue(playlistVideoRepo.getAllPlaylistSongs(strings[0]));
return null;
}
}}
存储库:
class PlaylistVideoRepo {
private final PlaylistSongDao playlistSongDao;
PlaylistVideoRepo(Application application) {
AppDatabase appDatabase = AppDatabase.getDatabase(application);
playlistSongDao = appDatabase.playlistSongDao();
}
public List<PlaylistSong> getAllPlaylistSongs(String playlistId) {
return playlistSongDao.getAllPlaylistSongs(playlistId);
}
public void delete(String path) {
new DeletePlaylistVideoAsyncTask(playlistSongDao).execute(path);
}}
道:
@Dao
public interface PlaylistSongDao {
@Query("SELECT * FROM " + PlaylistVideoConstants.TABLE_NAME +
" WHERE " + PlaylistVideoConstants.Columns.PLAYLIST_ID + " = :playlistId")
List<PlaylistSong> getAllPlaylistSongs(String playlistId);
@Query("DELETE FROM "+ PlaylistVideoConstants.TABLE_NAME + " WHERE " + PlaylistVideoConstants.Columns.PATH + " = :path")
void delete(String path);}
现在的问题是每当我要删除任何数据时。我的观察者没有收到任何回调。
如果我做错了什么,请纠正。
【问题讨论】:
-
您找到解决方案了吗?我想知道同样的事情。
标签: android android-architecture-components android-livedata