如何使用异步函数

时间:2015-12-14 11:02:53

标签: android asynchronous android-recyclerview

每次用户启动活动时,我都会尝试更新我的回收站视图。所有数据都保存在SQLite中。

我正在做的简单方法是清除附加到适配器的列表并添加一个像这样的新列表。

 public void set(List<contacts> list) {
        final sql s = sql.getInstance(getContext());


       if (ContactsList != null) {
           ContactsList.clear();
           ContactsList.addAll(list);
           cAdapter.notifyDataSetChanged();
       }

    }

此功能正常,但耗费大量内存

Skipped xx frames! The application may be doing too much work on its main thread.

我可以在后台使用handler吗?

有没有办法用另一个列表async

更新回收站视图

2 个答案:

答案 0 :(得分:1)

您需要查看主线程(可能是SQL查询)的时间,并将其从UI移开。

我强烈建议两件事:

  1. 正在运行traceview
  2. 使用Loaders进行SQL连接

答案 1 :(得分:-1)

我希望你的适配器中有一个元素列表,addAll只是添加到你的列表中。

所以你可以做的是创建新的Thread(AsyncTask,如果你愿意)并在Ui Thread上运行notifyDataSetChange。像

这样的东西
    public void set(List<contacts> list) {
            final sql s = sql.getInstance(getContext());


           if (ContactsList != null) {
               new Thread(new Runnable() {
                  @Override
                  public void run() {
                        ContactsList.clear();
                        ContactsList.addAll(list);
                        new Handler(Looper.getMainLooper()).post(
                           new  Runnable() {Handler(Looper.myLopper()) 
                                  @Override
                                  public void run() {                                                       
                                  ContactsList.notifyDataSetChanged();
                                  }
                              }); 
                            }
                        }.start
           }

        }
相关问题