Skip to content Skip to sidebar Skip to footer

Setting Image From Url To Imageview With Asynchtask

I have an image on my website, that I want to set on my ImageView. Do to that I needed to use an asynch task. I'm doing it like below. But new getThumbnail().execute(stringThumbnai

Solution 1:

The problem is in async task use it like this

publicclassMainActivityextendsActivity {

    privateImageView mThumbnail;
    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mThumbnail = (ImageView) findViewById(R.id.btnThumbnail);
        String stringThumbnail = "myImage.jpg";
        newgetThumbnail().execute(stringThumbnail);

    }

    classgetThumbnailextendsAsyncTask<String, Void, Bitmap> {

        protectedBitmapdoInBackground(String... data) {
            String thumb = data[0];
            Bitmap bitmap = null;
            try {
                Log.d("TEST", "do in background");
                bitmap = BitmapFactory
                        .decodeStream((InputStream) newURL(
                                "http://mySite.com/images/" + thumb)
                                .getContent());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        protectedvoidonPostExecute(Bitmap img) {
            Log.d("TEST", "post execute");
            mThumbnail.setImageBitmap(img);
        }
    }

}

also make sure that btnThumbnail is a imageView. Prefix btn is confusing and also declare the permission

<uses-permissionandroid:name="android.permission.INTERNET"/>

in the manifest.xml

Post a Comment for "Setting Image From Url To Imageview With Asynchtask"