2017-06-13 19 views
4

對不起,我的英語水平。我有列表對象,它列表包含開關btn。當用戶更改某些開關時,我需要它在db中更新。我 但是當我嘗試改變開關等,我有錯誤:廣東話實時更新recycleView蒙山境界

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 

} 
+0

您是否嘗試過第一次刷新recyclerview,這樣的佈局會刷新代碼是無效()。建議有很多實時數據庫在市場上現在例子火力點,你必須檢查了這一點。 – MuTiny

回答

6

您需要交易來修改RealmObject秒。

所以,你應該得到Realm實例docTypes屬於然後:

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

哇!非常感謝!你讓我開心) –