android.os.NetworkOnMainThreadException in AsyncTask's doInBackground

前端 未结 2 872
太阳男子
太阳男子 2020-12-02 00:31

Why do I get in an AsyncTask which should a android.os.NetworkOnMainThreadException? I thought that an AsyncTask is the solution to that problem. The exxeption is on line 7.

相关标签:
2条回答
  • 2020-12-02 00:52

    Best way to download an image and attach it to a ImageView is passing the ImageView as the parameter in your async task and set the URL as a tag of the image view then after downloading the task in the OnPostExecute() set the image to the ImageView look at this example :

    public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
    
    ImageView imageView = null;
    
    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return download_Image((String)imageView.getTag());
    }
    
    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }
    
    
    private Bitmap download_Image(String url) {
        ...
    }
    

    And the Usage will be like this

    ImageView mChart = (ImageView) findViewById(R.id.imageview);
    String URL = "http://www...someImageUrl ...";
    
    mChart.setTag(URL);
    new DownloadImageTask.execute(mChart);
    

    The image will be attached automatically when done, for more memory optimization you could use WeakReference.

    Good Luck.

    0 讨论(0)
  • 2020-12-02 01:08

    By calling doInBackground() directly, you are not actually using the AsyncTask functionality. Instead, you should call execute() and then use the results by overriding the AsyncTask's onPostExecute() method as explained in the Usage section of that same page.

    0 讨论(0)
提交回复
热议问题