【问题标题】:How to use Two NotifyDataSetChanged() Atomically如何以原子方式使用两个 NotifyDataSetChanged()
【发布时间】:2021-01-31 05:38:48
【问题描述】:

总结一下我的问题:

我有一个项目列表和一个按钮,我可以单击它来查询 API

当我单击按钮时,会调用两个方法。第一种方法显示进度条,清空列表,使用notifyDataSetChanged()

public void methodOne(){
      mProgressBar.setVisibility(View.VISIBLE);
      mList.clear;
      mAdapter.notifyDataSetChanged();
}

第二种方法使用retrofit进行查询,在回调方法中,我隐藏进度条,添加到列表中调用notifyDataSetChanged();

public void methodTwo(){
      RetrofitInterfaces.SearchForPosts service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.SearchForPosts.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            @Override
            public void onResponse(@NonNull Call<Feed> call, @NonNull Response<Feed> response) {
               
                try{

                   mProgressBar.setVisibility(View.INVISIBLE);
                   mList.addAll(response.body().getData()); 
                   mAdapter.notifyDataSetChanged();

                } catch(Exception e){
                   Log.e(TAG, "Error: " + e);
                }
                
            }

            @Override
            public void onFailure(@NonNull Call<Feed> call, @NonNull Throwable t) {
                Log.e(TAG, "onFailure: " + t);
     
            }
        });
    }

}

我的问题是当我一个接一个地调用这两个时:

methodOne();
methodTwo();

第二个带有改造调用的方法有时会返回一个 IndexOutOfBounds 异常,因为我在编辑 mList 时 methodOne() 调用了 mList.clear()mAdapter.notifyDataSetChanged();

我的问题是如何让这两者原子发生,这样它们就不会相互干扰? (我希望 methodOne() 甚至在查询发生在 methodTwo 之前做所有事情)

【问题讨论】:

    标签: android android-recyclerview retrofit retrofit2 android-threading


    【解决方案1】:

    您可以使用 AsyncTask,它会在 methodOne() 执行完毕时执行 methodTwo()

    private class MethodsTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            methodOne();
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            methodTwo();
        }
    }
    

    所以不要调用这两个方法

    methodOne();
    methodTwo();
    

    使用这个

    MethodsTask task = new MethodsTask();
    task.execute();
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 2014-12-06
      • 2016-06-07
      • 1970-01-01
      相关资源
      最近更新 更多