我正在尝试解析本网站文章的标题并将它们显示在 android 应用程序的列表视图中。我的代码如下所示:
public class MainActivity extends Activity {
ArrayList<String> mTitles = new ArrayList<String>();
ListView mListView;
ArrayAdapter<String> mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
processTitles();
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mTitles);
mListView.setAdapter(mAdapter);
}
private void processTitles() {
String URL = "http://beep.tv2.dk/nyheder";
try {
Document doc = Jsoup.connect(URL).userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19").timeout(10000).get();
Elements titles = doc.select("h2[class=title");
for(Element title: titles) {
mTitles.add(title.text());
}
if(mTitles.size() == 0) {
mTitles.add("Empty result");
}
} catch (Exception ex) {
ex.printStackTrace();
mTitles.clear();
mTitles.add("Exception: " + ex.toString());
}
}
}
尽管在这里阅读了很多关于 Stack Overflow 的文章,但我无法弄清楚为什么我的应用每次打开时都会崩溃。