0

总结一下我的问题:

我有一个项目列表和一个单击以查询 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 异常,因为 methodOne() 调用mList.clear()并且mAdapter.notifyDataSetChanged();当我对 mList 进行编辑时。

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

4

1 回答 1

0

您可以使用 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();
于 2020-10-16T18:11:30.330 回答