android.os.NetworkOnMainThreadException

徘徊边缘 提交于 2019-11-28 12:58:49

onPostExecute and onPreExecute methods of Asynctask runs into main thread of application. doInBackground method runs into another thread, which means that you should download your image into doInBackground method.

For example if you want to download image from some URL and then put that image into ImageView:

call:

new DownloadImageTask(yourImageView).execute(yourURL);

where asynctask class is:

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    private ProgressDialog mDialog;
    private ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected void onPreExecute() {

        mDialog = ProgressDialog.show(ChartActivity.this,"Please wait...", "Retrieving data ...", true);
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", "image download error");
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        //set image of your imageview
        bmImage.setImageBitmap(result);
        //close
        mDialog.dismiss();
    }
}

Also getting the image should be done somehow in the doInBackground method..as doing it in the onPostExecute is like doing it in the main thread not in background..

try this code

URL urll = new URL(url);
InputStream in = (InputStream) urll.openConnection().getInputStream();
bitmap = BitmapFactory.decodeStream(in);
Daryn

Try this:

AQuery aq = new AQuery(getActivity());
aq.id(view.findViewById(R.id.image)).image(imageUrl, true, true, 0,  0,
    new BitmapAjaxCallback() {
        @Override
        public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
            iv.setImageBitmap(bm);
        }
    }.header("User-Agent", "android"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!