I am trying to implement Favorite List in my Application. For that I am using realm as my database to store the Contents. I am able to add the contents successfully but when trying to remove the items crashes the app. I am trying to delete the objects using the primary key which is movieId variable. But it crashes the app. Any Help is Appreciated.
Code for adding and removing the contents:
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();
}
}
});
Once the method clear()
is deprecated, you should use:
realm.deleteAll()
or
results.deleteAllFromRealm()
Source: Realm Documentation
Instead of this
mRealm.beginTransaction();
mResults.remove(results);
mRealm.commitTransaction();
use clear()
method ( https://realm.io/docs/java/latest/api/io/realm/RealmResults.html#clear-- )
mRealm.beginTransaction();
results.clear();
mRealm.commitTransaction();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.