执行AsyncTask时出错

时间:2015-08-30 15:56:04

标签: android android-asynctask

我的应用程序在连接到互联网时工作正常, 但是当没有互联网连接时,它会崩溃。

public static final String URL =
        "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView imageView;

ImageButton imageButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    imageView = (ImageView) findViewById(R.id.imageView);

    imageButton=(ImageButton)findViewById(R.id.imgb);
    // Create an object for subclass of AsyncTask
    GetXMLTask task = new GetXMLTask();
    // Execute the task
    task.execute(new String[] { URL });
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        imageButton.setImageBitmap(result);
    }

    // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.
                    decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

logcat的:

08-30 21:22:08.325  32554-32577/com.android.cardview E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.android.cardview, PID: 32554
    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.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
            at com.android.cardview.ImageViewFromURLActivity$GetXMLTask.downloadImage(ImageViewFromURLActivity.java:80)
            at com.android.cardview.ImageViewFromURLActivity$GetXMLTask.doInBackground(ImageViewFromURLActivity.java:52)
            at com.android.cardview.ImageViewFromURLActivity$GetXMLTask.doInBackground(ImageViewFromURLActivity.java:43)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)

1 个答案:

答案 0 :(得分:1)

你必须有互联网访问才能获得该图像,如果不是空的例外将会发生。

要知道您是否有连接,您必须使用以下内容:

public static boolean testConection(Context context){
        boolean HaveConnectedWifi = false;
        boolean HaveConnectedMobile = false;
        boolean result;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo)
        {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    HaveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    HaveConnectedMobile = true;
        }
        result = HaveConnectedWifi || HaveConnectedMobile;
        return result;
    }

将它放在Utils类或类似的类上。然后,在你的主Activity(或片段,无关紧要)中使用它:

boolean connready = Utils.testConection(getActivity());
        if (connready) {
            // Here goes your code if connection is true
            task.execute(new String[] { URL });
        } else {
            // Here you can send alerts to users without connection
            Toast.makeText(getActivity(), "check your connection", Toast.LENGTH_SHORT).show();

        }

这对用户来说将更加友好。希望对你有帮助!