Cant realtime update recycleView with scope

Sorry for my English. I have list objects, there is switch btn in the list. When the user changes some kind of switch, I update it in db. I But when I try to change swith, I have an error:

java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction.

I can’t figure out how to create an adapter that can update data in real time.

My adapter :

   public class DocumentTypeAdapterDB extends RealmRecyclerViewAdapter<DocType, DocumentTypeAdapterDB.ViewHolder> {

    RealmList<DocType> docTypes;

    public DocumentTypeAdapterDB(@Nullable RealmList<DocType> docTypes, Context context) {
        super(docTypes, true);
        this.docTypes = docTypes;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_doc_type, null);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutView.setLayoutParams(lp);
        ViewHolder rcv = new ViewHolder(layoutView);
        return rcv;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final DocType docType = docTypes.get(position);

        holder.switch_item.setText(docType.name);



        //check box
        holder.switch_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!holder.switch_item.isChecked()) {
                    docType.is_check = false;
                } else {
                    docType.is_check = true;
                }
            }
        });

    }


    @Override
    public int getItemCount() {
        return docTypes.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        SwitchCompat switch_item;

        public ViewHolder(View itemView) {
            super(itemView);
            switch_item = (SwitchCompat) itemView.findViewById(R.id.switch_item);
        }

        public void clearAnimation()
        { itemView.clearAnimation(); }
    }


}

Doctype

public class DocType extends RealmObject{
public boolean is_check;
    public String name;
    //getter and setter

}
+4
source share
1 answer

Changing RealmObjects requires a transaction.

So, you should get the instance Realmto which it belongs docTypes, and then:

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        docType.is_check = holder.switch_item.isChecked();
    }
});
+7
source

Source: https://habr.com/ru/post/1679120/


All Articles