【问题标题】:Wait onPostExecute finish to make new adapter等待 onPostExecute 完成以制作新适配器
【发布时间】:2020-02-10 13:42:36
【问题描述】:

我尝试用 Tmdb api 找一些电影,但我遇到了问题。

每次我在EditText 上做某事时,我都需要执行 Asynctask,但任务更长。

这样可以等到fetchData上的onPostExecute没有完成吗?

制作 AsyncTask 的 fetchData 类:

protected Void doInBackground(Void... voids) {
    //make things...
}
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    SearchActivity.listFinale = list;
}

我的 SearchActivity 的一部分:

public static RecyclerView rv;
public static ArrayList<Movie> listFinale = new ArrayList<Movie>();

recherche.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                fetchData process = new fetchData(recherche.getText().toString());
                process.execute();


                //I want to do this part when onPostExecute is finish
                rv.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
                MyAdapter mMyadapter= new MyAdapter(listFinale);
                rv.setAdapter(mMyadapter);
                mMyadapter.setonItmeClickListener(SearchActivity.this);
               //

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

【问题讨论】:

    标签: java android asynchronous android-asynctask


    【解决方案1】:

    我的建议是你可以学习改造,rxjava rxandroid(反应式编程)库。通过这种方式,您可以与接口进行通信。 您可以创建一个接口并在 SearchActivity 中实现。

    public interface IResultListener {
      void onResult(List<BlaBlaModel> list);
    }
    

    然后,在 SearchActivity 中实现。

    private IResultListener resultListener = new IResultListener() {
        @Override
        public void onResult(List<BlaBlaModel> list) {
            // do anything...
        }
    };
    

    然后我们将这个接口对象分配给 asynctask。结果完成后,我们使用这样的接口对象将列表发送到 SearchActivity。

    protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
         if (listener != null) {
            listener.onResult(list)
         }
    }
    

    【讨论】:

    • 感谢您的回答,但我需要:更改 EditText -> 获取 EditText 值 -> 使用该值执行 fetchData 并将新列表发送到我的活动 -> 使用新列表创建新适配器。实际上,我不明白为什么您的解决方案会停止 onTextChanged 部分中的线程,并在 onPostExecute 完成后继续
    • Android 应用程序运行 UI 线程。 Asynctask 允许您执行后台操作。因此,当您使用 Asynctask 时,进程是在另一个线程中进行的。 ui 线程继续运行,无需等待其他线程附加。在您的代码中,您调用 fetchData 并启动进程,但您不听结果。在结果出来之前,可以创建适配器并重新分配给recyclerview。为此,我需要知道该过程已经结束,之后我可以进行必要的操作。
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多