AsyncTask抛出一个InvocationTargetException

时间:2012-05-08 00:04:11

标签: java android

我有一个使用AsyncTask的简单Activity

EditText txt;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .detectNetwork().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    txt = (EditText) findViewById(R.id.edit_message);
    setContentView(R.layout.main);
}
public void connectToNetwork(View view)
{
    String address = "https://www.google.com";
        new DownloadWebpageText().execute(address);

}
private class DownloadWebpageText extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... params)
      {
       return params[0] + ",Some thing";

      }

   @Override
   protected void onPostExecute(String result)
      {
       txt.setText(result); //this is an EditText

      }

}

我为了简洁而简化了代码,但它抛出了InvocationTargetException并且没有执行onPostExecute方法。我在调试时无法理解任何内容。有什么帮助吗?

Logcat错误:

05-08 00:16:44.045: E/AndroidRuntime(537): FATAL EXCEPTION: main
05-08 00:16:44.045: E/AndroidRuntime(537): java.lang.NullPointerException
05-08 00:16:44.045: E/AndroidRuntime(537):  at myApp.src.MyAppActivity$DownloadWebpageText.onPostExecute(MyAppActivity.java:162)
05-08 00:16:44.045: E/AndroidRuntime(537):  at myApp.src.MyAppActivity$DownloadWebpageText.onPostExecute(MyAppActivity.java:1)
05-08 00:16:44.045: E/AndroidRuntime(537):  at android.os.AsyncTask.finish(AsyncTask.java:602)
05-08 00:16:44.045: E/AndroidRuntime(537):  at android.os.AsyncTask.access$600(AsyncTask.java:156)
05-08 00:16:44.045: E/AndroidRuntime(537):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
05-08 00:16:44.045: E/AndroidRuntime(537):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 00:16:44.045: E/AndroidRuntime(537):  at android.os.Looper.loop(Looper.java:137)
05-08 00:16:44.045: E/AndroidRuntime(537):  at android.app.ActivityThread.main(ActivityThread.java:4424)
05-08 00:16:44.045: E/AndroidRuntime(537):  at java.lang.reflect.Method.invokeNative(Native Method)
05-08 00:16:44.045: E/AndroidRuntime(537):  at java.lang.reflect.Method.invoke(Method.java:511)
05-08 00:16:44.045: E/AndroidRuntime(537):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-08 00:16:44.045: E/AndroidRuntime(537):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-08 00:16:44.045: E/AndroidRuntime(537):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

您是否需要设置内容视图然后查看视图?

setContentView(R.layout.main);
txt = (EditText) findViewById(R.id.edit_message);

答案 1 :(得分:1)

鉴于NullPointerException的来源(onPostExecute()),txt显然是null