我需要一些建议,因为这件事使我花了足够的时间来对自己的知识缺乏生气……我试图使由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片段解析数据:
<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代码中存在的其他标题。单独的解析部分也很好。 最佳答案
您必须在适配器上调用notifyDataSetChanged
在提供给适配器的列表中反映更改。要做到这一点 -
覆盖onPostExecute
中的NewThread
并调用mAdapter.notifyDataSetChanged()
@Override
protected void onPostExecute(String result) {
mAdapter.notifyDataSetChanged();
}
注意:
onPostExecute
在主UI线程上运行,而不是在NewThread
上运行,而doInBackground
在NewThread
内部运行。并且在后台线程完成处理后调用onPostExecute
。现在,由于我们已经用新项目更新了列表。我们将通知适配器在主线程上运行。希望能帮助到你。