无法实时更新recycleView whith领域

Про*_*тлг 4 android realm android-recyclerview

对不起我的英语不好.我有列表对象,它列表包含switch btn.当用户更改某些交换机时,它会在db中更新.我但是当我尝试改变开关时,我有错误:

java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction.
Run Code Online (Sandbox Code Playgroud)

我无法理解如何创建适配器,谁可以更新实时数据

我的适配器:

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


}
Run Code Online (Sandbox Code Playgroud)

的DocType

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

}
Run Code Online (Sandbox Code Playgroud)

小智 13

您需要事务来修改RealmObjects.

所以,你应该得到属于的Realm实例,docTypes然后:

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        docType.is_check = holder.switch_item.isChecked();
    }
});
Run Code Online (Sandbox Code Playgroud)