Sorry for my english. I have list objects, it list contains switch btn. When user change some switch i neeed it update in db. I But when i try change swith, i have error:
java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction.
I can not understand how create adapter, who can update realtime data
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
}
You need transaction to modify RealmObjects.
So, you should get Realm instance that docTypes belongs to and then:
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        docType.is_check = holder.switch_item.isChecked();
    }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With