从onActivityResult()调用时,notifyDataSetChanged()不能使用我的RecyclerView.Adapter

时间:2016-06-19 16:26:28

标签: java android android-recyclerview onactivityresult notifydatasetchanged

在用户返回原始活动后调用onActivityResult()时,我会更新RecyclerView的数据并致电notifyDataSetChanged(),但未调用onBindViewHolder()且{ {1}}不会更新。

如果我运行相同的代码来从RecyclerView触发器更新Recylerview,则onClick() 正确更新。仅当从RecyclerView调用更新代码时,onActivityResult()才会更新。

我尝试使用RecylerView方法运行更新方法来更新RecylerView,但这并没有解决问题。我还尝试了runOnUiThread()的所有相关通知方法(即notifyDataSetChanged()等),但为了简单起见,我将仅提及RecyclerView.Adapter

这是问题的基本再现:

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()触发器调用时,RecyclerView方法正确更新了onClick(),似乎该方法配置正确。我尝试向onActivityResult添加延迟,这会在运行RecylervView方法之前为refreshData()时间加载任何数据,但这并没有解决问题。

任何人都可以在我的代码中看到任何问题或告诉我如何解决这个问题?

我查看了其他SO问题,但我无法找到解决此问题的适用方法。

提前致谢

1 个答案:

答案 0 :(得分:1)

确保您已拨打:

finish();

setResult

setResult(Adapter.REQUEST_CODE, usefulIntent);

为了触发onActivityResult

另外如果:

notifyDataSetChanged();

无法考虑重置

setAdapter();