我需要一些建议,因为这件事花了我足够的时间对自己缺乏知识感到愤怒......我尝试制作一个由 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/