Coding John
Coding John

Reputation: 53

Delete RealmObject displayed in a RecyclerView

I wanna display some RealmObjects(ideas) from a RealmList (ideaList) to a Recyclerview. Sounds easy. But when i try to delete an Object, it's though there when i do a Query(for getting all ideas from a specific user)

Code examples:

query:

public RealmList<Idea> getIdeaListFromRealm(Context ctx) {
    realm = Realm.getInstance(ctx);
    RealmQuery<Idea> ideaQuery = realm.where(Idea.class);
    RealmResults<Idea> ideaQueryResults = ideaQuery.equalTo("owner.id",""+LoginFragment.loggedOwner.getId()).findAll();
    RealmList<Idea> ideaList = new RealmList<>();
    ideaList.addAll(ideaQueryResults);
    return ideaList;
}

delete(onClick) :

holder.delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            realm.beginTransaction();
            ideaList.remove(position);
            notifyDataSetChanged();
            realm.commitTransaction();
            fragmentStateHandler.replaceFrag(Frag.ARCHIVEFRAGMENT);
        }
    });

I think i did not delete it properly. There can be no other reason, because it's still there in the query after deleting.

What am i doing wrong? thanks in advance

Upvotes: 0

Views: 1232

Answers (1)

marius
marius

Reputation: 7806

You're removing the object just from the RealmList, which isn't persisted at all.

You've to delete the object either from the results or just directly going over the object instance. e.g.

 realm.beginTransaction();

 ideaQueryResults.remove(position);

 // alternatively:

 Idea idea = ideaQueryResults.get(position);
 idea.removeFromRealm();

 realm.commitTransaction();

 // from the docs: it will always be more efficient to
 // use the more specific change events if you can.
 // Rely on notifyDataSetChanged() as a last resort.
 notifyItemRemoved(position);

Upvotes: 2

Related Questions