AsyncTask类运行时错误:concurrent.FutureTask.finishCompletion

时间:2014-12-13 05:41:22

标签: java android android-asynctask

我是android的新手并尝试制作可以在 AsyncTask类中打印变量的简单程序 这是我的代码

    int a,b,c;
@Override
protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub
a =10;
b=10;
c=a+b;
Context ctx = null;
show(c, ctx );


return null;

}
public  void show(int c2 ,Context c) {
    // TODO Auto-generated method stub

    Toast.makeText(c, "AsyncTask classs + c2 ", Toast.LENGTH_SHORT).show();

}

运行此程序后,我得到运行时错误

这里是我们的LogCat文件视图

  Process: com.example.asycclass, PID: 2539
  java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:300)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:841)
  Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:200)
    at android.os.Handler.<init>(Handler.java:114)
    at android.widget.Toast$TN.<init>(Toast.java:327)
    at android.widget.Toast.<init>(Toast.java:92)
    at android.widget.Toast.makeText(Toast.java:241)
    at com.example.asycclass.MainActivity$AttemptLogin.show(MainActivity.java:74)
    at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:65)
    at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)

2 个答案:

答案 0 :(得分:2)

在runOnUiThread中移动show Toast代码,如:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
       show(c, ctx );
    }
});

答案 1 :(得分:1)

我想问题是您尝试不是从主线程创建Toast。 您必须为此创建handlerRunnable并使用handler.post()

例如

Runnable showToast = new Runnable() {
    public void run() {
        // Create your Toast here or whatever you want
    }
}