无法实时更新recycleView whith领域

时间:2017-06-13 08:41:08

标签: android android-recyclerview realm

抱歉我的英文。我有列表对象,它列表包含switch btn。当用户更改某些交换机时,它会在db中更新。一世 但是当我尝试改变开关时,我有错误:

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

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

我的适配器

   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

}

1 个答案:

答案 0 :(得分:13)

您需要事务来修改RealmObject s。

因此,您应该获得Realm所属的docTypes个实例,然后:

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