java - 如何在不卡住程序的情况下更新ListView

标签 java android multithreading

所以我有一个 strings (ISBN) 列表,我需要用与这些 strings< 关联的对象(Book 对象)填充 listview/。问题是我必须使用字符串获取 Book 对象的函数需要时间,因此要获取 30 本书,等待时间接近 4 或 5 秒。

我想到的一种方法是一次获取一个 Book 对象,并在获取它们时将它们添加到列表中。但此过程将卡住 UI,直到完成所有添加。如果我尝试将这个进程放在一个新线程中,它不会让我添加到任何 UI 对象(因为它来自另一个线程)。如果我尝试将它放在 AsyncTask 中,我将无法访问 ListView,因为它位于 MainActivity 类中。

肯定有一种方法可以动态更新 UI 元素,我确定我已经看到了。有什么建议吗?

编辑:

这是我用来向列表实际添加项目的代码:

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}

最佳答案

你能像这样对你的代码进行一些更改吗?它很简单,它认为它会起作用

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
SearchBookDataProvider dataProvider;
listView.setAdapter(bookAdapter);

 new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] objects) {
                for(int i = 0; i < searches.size(); i++) {

                //Get the book
                Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

                //Assign data to the adapter variables
                Bitmap cover = book.getCover();
                String title = book.getTitle();
                String author = book.getAuthor();

                //Add data to the adapter and set the list
                dataProvider = new SearchBookDataProvider(cover, title, author);
                bookAdapter.add(dataProvider);
                }
            }
            @Override
            protected void onPostExecute(Object o) {
                if (bookAdapter!= null) {
                    bookAdapter.notifyDataSetChanged();
                }
                super.onPostExecute(o);
            }
 }.execute();

关于java - 如何在不卡住程序的情况下更新ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47626522/

相关文章:

java - Lucene 不同的结果

android - 一次可以调用多少hashMap操作 'safe'

android - 如何在 float 操作按钮的背景中设置图像而不是 android 中的颜色?

java - 通过重写 afterExecute(Runnable r, Throwable t) 可重试线程池

python - python中多线程应用程序中的段错误错误

java - 反引号准备好的语句 Java

java - 避免 for 循环并尝试使用集合 API(性能)

java - 类变量声明意外结束

c# - 异步方法?

面向对象的Java : how to create objects properly