java - 从 onActivityResult() 调用时,notifyDataSetChanged() 不适用于我的 RecyclerView.Adapter

标签 java android android-recyclerview onactivityresult notifydatasetchanged

当用户返回原始 Activity 后调用 onActivityResult() 时,我会更新 RecyclerView 的数据并调用 notifyDataSetChanged()但是 onBindViewHolder() 没有被调用并且 RecyclerView 没有更新。

如果我运行相同的代码从 onClick() 触发更新 Recylerview,RecyclerView 正确更新。只有当 onActivityResult() 调用更新代码时,RecylerView 才不会更新。

我尝试通过使用 runOnUiThread() 方法运行更新方法来更新 RecylerView,但这并没有解决问题。我还尝试了 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();

关于java - 从 onActivityResult() 调用时,notifyDataSetChanged() 不适用于我的 RecyclerView.Adapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37909386/

相关文章:

java - Android 在用户使用 HashMap TransactionTooLargeException 加载 MainActivity 之前在预览屏幕上传递大数据

java - 无法从 javafx 中的另一个 Controller 更新场景

android - 强制 Gradle 使用 HTTP 而不是 HTTPS

android - 如何从 LayoutManager View (RecyclerView) 获取适配器项对象

java - RecyclerView 不接受模型中的构造函数

java - 为什么无参数构造函数会在无效状态下被实例化?

java - 提供 BufferedImage 时 Spring MVC 内容协商失败

android - eclipse 集成开发环境 : Failed to initialize monitor thread error after installing Android SDK?

android - Google Play 发布 支持的设备 0

android - 如何使用 Snackbar 撤消操作绕过删除 SQLite 数据