java - Android - 使用 JSOUP 实现具有 AsyncTask 的 ListView

标签 java android html android-asynctask jsoup

我需要一些建议,因为这件事花了我足够的时间对自己缺乏知识感到愤怒......我尝试制作一个由 JSOUP 提取的数据填充的 ListView。而JSOUP部分在AsyncTask中。这是我的代码:

public class ListaActivity extends ActionBarActivity {

    private List<String> mList = new ArrayList<>();
    private ListView mListView;
    private ListAdapter mAdapter;

    public Elements job;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);  

        mListView = (ListView) findViewById(R.id.list);

        new NewThread().execute();
        mAdapter = new ListAdapter(this, mList);
        mListView.setAdapter(mAdapter);
    }

    public class NewThread extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... arg) {

            Document doc;
            try {
                doc = (Document) Jsoup.connect("http://www.somewebsite.com")
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();

                title = doc.select("h3.something-to-extract a[href]");

                for (Element titles : title) {
                    mList.add(titles.text()+"\n");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}

IMO 它是 JSOUP 部分的东西,因为当我删除所有内容 od doInBackground 并放入其中

mList.add("Something 1");
mList.add("Something 2");

然后就可以了。请以某种方式帮助我。

编辑:我想解析此 html fragment 中的数据:

<h2 class="title">
      <a href="/jstpl/london/11697582"  
               title="You just have to wait" class="titles">
                    Nothing else to say
       </a>

我想将“Nothing else to say”存储到mList,例如我的html代码中存在的另一个标题。单独的解析部分也很好用。

最佳答案

You have to call notifyDataSetChanged on adapter

反射(reflect)提供给适配器的列表中的更改。为此 -

NewThread 中覆盖 onPostExecute 并调用 mAdapter.notifyDataSetChanged()

        @Override
        protected void onPostExecute(String result) {
            mAdapter.notifyDataSetChanged();
        }  

注意: onPostExecute 在主 UI 线程上运行,而不是在 NewThread 上运行,而 doInBackground 在内部运行你的NewThread。当后台线程完成处理时,会调用onPostExecute。现在我们已经用新项目更新了列表。我们将通知在主线程上运行的适配器。希望对您有所帮助。

关于java - Android - 使用 JSOUP 实现具有 AsyncTask 的 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30243472/

相关文章:

android - 使用 jQuery "swipe"函数导航图像数组

android - 在android内存监视器中, `total count` 和 `heap count` 有什么区别?

javascript - 在简单的碰撞检测算法方面需要帮助

html - CSS/HTML : input bar width and button width not the same even though I'm setting it as the same

java - 如何将 HttpResponse 下载到文件中?

java - 为 XNAT 导入 Gradle 项目时出现问题 - Unresolved 类型

java - 如何使用java中的多线程对记录列表进行排序?

java - 为什么我收到死代码警告?

android - Flutter:如何保持应用程序在后台运行

html - CSS3文本框水平对齐,间隔一个曲率