簡體   English   中英

從onActivityResult()調用時,notifyDataSetChanged()不能與我的RecyclerView.Adapter一起使用

[英]notifyDataSetChanged() doesn't work with my RecyclerView.Adapter when it's called from onActivityResult()

onActivityResult()用戶返回到原來的活動之后叫我更新的數據RecyclerView並調用notifyDataSetChanged()onBindViewHolder()沒有被調用, RecyclerView不更新。

如果我運行相同的代碼來從onClick()觸發器更新Recylerview,則RecyclerView 正確更新。 只有當從onActivityResult()調用更新代碼時, RecylerView才會更新。

我試圖更新RecylerView運行使用的更新方法runOnUiThread()方法,但沒有解決問題。 我還嘗試了RecyclerView.Adapter所有相關通知方法(即notifyDataSetChanged()等),但為簡單起見,我將僅引用notifyDataSetChanged

這是問題的基本再現:

   //This code is in the Adapter, it removes an item from the arrayList and updates the RecylerView.     
     protected void refreshData(int position){
        arrayListData.remove(position);
        notifyDataSetChanged ();
    }


    //This code is in the ViewHolder. When refreshData() is called via the onClick() here the **RecylerView does successfully update** 
     @Override
            public void onClick(View v) {        
             if (shouldRefreshData == true) {     
               refreshData(getAdapterPosition()); 
          } else {
                Intent secondActivity = new Intent(context, SecondActivity.class);
((Activity)context).startActivityForResult(secondActivity, Adapter.REQUEST_CODE); 
         }
    }

//I set the result code is in the Second Activity like this
 setResult(Adapter.REQUEST_CODE, usefulIntent);


//This code is in the original activity, it successfully runs, and the refreshData() method is called and I can see the data has been removed via log statements in the refreshData() method but the onBindViewHolder() method is never called
@Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
         if (requestCode == Adapter.REQUEST_CODE) {
    ....
    adapter.refreshData(positionRetrievedFromTheDataIntent);
     }
 }

看當refreshData()方法在通過onClick()觸發器調用時正確更新RecyclerView ,似乎該方法配置正確。 我嘗試在onActivityResult添加延遲,這會讓RecylervView在運行refreshData()方法之前加載任何數據,但這並沒有解決問題。

任何人都可以在我的代碼中看到任何問題或告訴我如何解決這個問題?

我已經查看了其他SO問題,但我找不到適用於此問題的解決方案。

提前致謝

確保您已撥打:

finish();

setResult

setResult(Adapter.REQUEST_CODE, usefulIntent);

為了觸發onActivityResult

如果:

notifyDataSetChanged();

沒有工作考慮重置

setAdapter();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM