android-如何在realm数据库中添加和删除对象?

时间:2016-03-27 14:18:30

标签: android realm

我正在尝试在我的应用程序中实现收藏列表。为此,我使用领域作为我的数据库来存储内容。我能够成功添加内容,但在尝试删除项目时会崩溃应用程序。我试图使用主键,即movieId变量删除对象。但它崩溃了应用程序。 感谢任何帮助。

添加和删除内容的代码:

       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();
                }
            }
        });

2 个答案:

答案 0 :(得分:4)

弃用方法realm.deleteAll() 后,您应该使用:

results.deleteAllFromRealm()

git config --get remote.origin.url

来源:type signature

答案 1 :(得分:2)

而不是这个

mRealm.beginTransaction();
mResults.remove(results);
mRealm.commitTransaction();

使用clear()方法(https://realm.io/docs/java/latest/api/io/realm/RealmResults.html#clear--

mRealm.beginTransaction();
results.clear();
mRealm.commitTransaction();