错误日志:
04-16 23:05:29.133: W/dalvikvm(7474): threadid=1: thread exiting with uncaught exception (group=0x41550930)
04-16 23:05:29.133: E/AndroidRuntime(7474): FATAL EXCEPTION: main
04-16 23:05:29.133: E/AndroidRuntime(7474): java.lang.NullPointerException
04-16 23:05:29.133: E/AndroidRuntime(7474): at com.example.yo.MainActivity$jsoupexample.onPostExecute(MainActivity.java:74)
04-16 23:05:29.133: E/AndroidRuntime(7474): at com.example.yo.MainActivity$jsoupexample.onPostExecute(MainActivity.java:1)
04-16 23:05:29.133: E/AndroidRuntime(7474): at android.os.AsyncTask.finish(AsyncTask.java:631)
04-16 23:05:29.133: E/AndroidRuntime(7474): at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-16 23:05:29.133: E/AndroidRuntime(7474): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-16 23:05:29.133: E/AndroidRuntime(7474): at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 23:05:29.133: E/AndroidRuntime(7474): at android.os.Looper.loop(Looper.java:137)
04-16 23:05:29.133: E/AndroidRuntime(7474): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-16 23:05:29.133: E/AndroidRuntime(7474): at java.lang.reflect.Method.invokeNative(Native Method)
04-16 23:05:29.133: E/AndroidRuntime(7474): at java.lang.reflect.Method.invoke(Method.java:511)
04-16 23:05:29.133: E/AndroidRuntime(7474): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-16 23:05:29.133: E/AndroidRuntime(7474): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-16 23:05:29.133: E/AndroidRuntime(7474): at dalvik.system.NativeStart.main(Native Method)
04-16 23:05:29.163: D/dalvikvm(7474): GC_CONCURRENT freed 557K, 9% free 8027K/8736K, paused 2ms+4ms, total 28ms
代码
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity {
Document doc;
TextView tv;
String res="";
String BLOG_URL = "http://www.google.co.in/";
@Override
public void onCreate(Bundle savedInstanceState) {
// set layout view
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new jsoupexample().execute(BLOG_URL);
}
public class jsoupexample extends AsyncTask<String,Integer,String>
{
@Override
protected String doInBackground(String... BLOG_URL) {
try {
doc= Jsoup.connect(BLOG_URL[0]).userAgent("Mozilla/5.0").timeout(20000).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Elements links = doc.select("a[href]");
for(Element element: links)
{
res = element.attr("href");
}
return res;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result!=null && !result.isEmpty())
tv.setText(result);
else
tv.setText("no value returned");
}
}
}
答案 0 :(得分:0)
tv
为空。在onCreate
初始化它:
tv = (TextView)findViewById(R.id.<the-id>);
答案 1 :(得分:0)
在您的onPstExecute()
方法中,您拥有以下内容:
tv.setText(结果);
你从未实例化tv
,因此它为空。当您尝试在null上调用方法时,会出现NullPointerException。