我将尝试在我的应用程序中实现收藏列表。为此,我使用realm作为数据库来存储内容。我能够成功地添加内容,但是在尝试删除项目时,应用程序会崩溃。我正在尝试使用电影ID变量作为主键来删除对象。但它导致了应用程序崩溃。
任何帮助都将不胜感激。
添加和删除内容的代码:
添加和删除内容的代码:
mFavoriteButton.setOnFavoriteChangeListener(new MaterialFavoriteButton.OnFavoriteChangeListener() {
@Override
public void onFavoriteChanged(MaterialFavoriteButton buttonView, boolean favorite) {
if(!favorite) {
SharedPreferences.Editor editor = getSharedPreferences("com.thejoker.yts", MODE_PRIVATE).edit();
editor.putBoolean("Fav Checked", false);
editor.commit();
RealmResults<FavoriteListRealm> results = mRealm.where(FavoriteListRealm.class).equalTo("realmMovieId", movieId).findAll();
mRealm.beginTransaction();
mResults.remove(results);
mRealm.commitTransaction();
Toast.makeText(getContext(), "Not a favorite", Toast.LENGTH_SHORT).show();
}
if(favorite) {
SharedPreferences.Editor editor = getSharedPreferences("com.thejoker.yts", MODE_PRIVATE).edit();
editor.putBoolean("Fav Checked", true);
editor.commit();
mRealm.beginTransaction();
FavoriteListRealm favorites = mRealm.createObject(FavoriteListRealm.class);
favorites.setRealmMovieId(movieId);
favorites.setRealmMovieTitle(movieTitle);
favorites.setRealmThumbnailUrl(movieUrlThumbnail);
favorites.setRealmMovieYear(movieYear);
mRealm.copyToRealmOrUpdate(favorites);
mRealm.commitTransaction();
mResults = mRealm.where(FavoriteListRealm.class).findAllAsync();
Toast.makeText(MovieDetailsActivity.this, mResults.toString(), Toast.LENGTH_LONG).show();
}
}
});