执行doInBackground时出错

时间:2017-01-22 13:27:29

标签: android-asynctask

执行doInBackground()

时发生错误

我是android studio的新手,我正在尝试下载不同的位图图片,以便通过AsyncTask class.my错误日志显示在imageview中:

FATAL EXCEPTION: AsyncTask #1
     Process: com.example.sayareh.http2, PID: 32302
        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:818)
        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:561)
        at android.widget.Toast.<init>(Toast.java:129)
        at android.widget.Toast.makeText(Toast.java:419)
        at com.example.sayareh.http2.MainActivity.OpenHttpConnection(MainActivity.java:65)
        at com.example.sayareh.http2.MainActivity.DownloadImage(MainActivity.java:75)
        at com.example.sayareh.http2.MainActivity.access$100(MainActivity.java:32)
        at com.example.sayareh.http2.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:87)
        at com.example.sayareh.http2.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:83)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        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:818) 

这是我的MainActivityClass:

public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView=(ImageView) findViewById(R.id.img);
    new DownloadImageTask().execute(
            "http://kocholo.org/img/images/lk4nnpetjq7rf10zf8r.jpg",
            "http://media.mnn.com/assets/images/2016/01/stern-baby.jpg.838x0_q80.jpg",
            "http://www.raisesmartkid.com/wp-content/uploads/baby-watching-tv.jpg",
            "http://creativemisha.com/wp-content/uploads/2014/07/Cute-Baby-Girl-HD-Wallpaper1.jpg");

}
private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream inputStream=null;
    int response=-1;
    URL url=new URL(urlString);
    URLConnection conn=url.openConnection();
    if(!(conn instanceof HttpURLConnection))
        throw  new IOException("Not an Http Connection");
    try {
        HttpURLConnection httpURLConnection=(HttpURLConnection) conn;
        httpURLConnection.setAllowUserInteraction(false);
        httpURLConnection.setInstanceFollowRedirects(true);
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();
        response=httpURLConnection.getResponseCode();
        if(response==httpURLConnection.HTTP_OK)
            inputStream=httpURLConnection.getInputStream();

    }catch (Exception ex){
        Toast.makeText(this, "NETWORKING" + ex.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        throw new IOException("errcoonnecting");
    }
    return inputStream;
}
private Bitmap DownloadImage(String url)
{
    Bitmap bitmap=null;
    InputStream inputStream=null;
    try{
        inputStream=OpenHttpConnection(url);
        bitmap= BitmapFactory.decodeStream(inputStream);
        inputStream.close();
    }catch (IOException io){
        Toast.makeText(this,io.getLocalizedMessage(),Toast.LENGTH_LONG).show();
    }
    return bitmap;
}
private class DownloadImageTask extends AsyncTask<String,Bitmap,Long> {
    protected Long doInBackground(String... urls) {
        long imgcounts =0;
        for (int i = 0; i < urls.length; i++) {
            Bitmap imagedownloaded = DownloadImage(urls[i]);
            if (imagedownloaded != null){
                imgcounts++;
            try {
                Thread.sleep(3000);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
            publishProgress(imagedownloaded);
        }}
        return imgcounts;
    }
    protected void onProgressUpdate(Bitmap... bitmaps)
    {
        imageView.setImageBitmap(bitmaps[0]);
    }

    protected void onPostExecute(Long imagedownloaded) {
        Toast.makeText(getBaseContext(),"h",Toast.LENGTH_LONG).show();
    }
}

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

在doInBackground()中创建和显示Toast消息(在你的情况下,在DownloadImage的catch语句中)导致了这一点。

由于doInBackground()在单独的线程上运行,而Toast需要UI Thread来显示Toast消息。

答案 1 :(得分:0)

从downloadimage方法中删除toast,ui你不能更新doin background()中的元素。

}catch (IOException io){
    Toast.makeText(this,io.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}