Currently following this tutorial Android XML Adventure – Parsing HTML using JSoup, app works in Emulator, but display Error in TextView on device.
I have copy and paste jsoup-1.7.2.jar into libs, set <uses-permission android:name="android.permission.INTERNET"/>
in AndroidManifest.xml and set TextView android:id="@+id/tv"
. And this is what my Project Explorer looks like.
Here is the JsoupActivity.java
package com.jsoupstudyactivity;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.view.Menu;
public class JSoupActivity extends Activity {
// blog url
static final String BLOG_URL = "http://xjaphx.wordpress.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// process
try {
((TextView)findViewById(R.id.tv)).setText(getBlogStats());
} catch (Exception ex) {
((TextView)findViewById(R.id.tv)).setText("Error");
}
}
protected String getBlogStats() throws Exception {
String result = "";
// get html document structure
Document document = Jsoup.connect(BLOG_URL).get();
// selector query
Elements nodeBlogStats = document.select("div#blog-stats-2 ul li");
// check results
if(nodeBlogStats.size() > 0) {
// get value
result = nodeBlogStats.get(0).text();
}
// return
return result;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.jsoup, menu);
return true;
}
}