0

I'm getting my image through an URL and trying to set that to my imageView. But I'm getting a Null Pointer Exception. It is not even entering my asynchtask.

Is there something I'm doing wrong or not seeing?

public class DetailsActivity extends Activity {
    ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);

        final Bundle extras = getIntent().getExtras();


        String img = extras.getString("Thumbnail");
        new DownloadImageTask((ImageView) findViewById(R.id.btnThumbnail))
                .execute("http://mysite.com/images/"
                        + img);


        }

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

        public DownloadImageTask(ImageView bmImage) {
            thumbnail = bmImage;
        }

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

        protected void onPostExecute(Bitmap result) {
            thumbnail.setImageBitmap(result);
        }
    }

}
mXX
  • 3,595
  • 12
  • 44
  • 61

1 Answers1

3
ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail);

You need to get your image after inflating the layout, otherwise findViewById will returns null :

ImageView thumbnail; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail);
    thumbnail = (ImageView) findViewById(R.id.btnThumbnail)
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • But I need that globally so I can use it in the asynchtask – mXX Jun 13 '13 at 19:22
  • Great this fixed it! Can't accept your answer, have to wait 10 min – mXX Jun 13 '13 at 19:24
  • 2
    @mXX: Your `AsyncTask` is broken in other ways anyhow. Notably, it will not handle configuration changes (e.g., screen rotation), as now the `AsyncTask` will work with the wrong `ImageView` from the wrong `Activity`. Please use libraries like Picasso that can offer you better patterns for asynchronous image loading: http://square.github.io/picasso/ – CommonsWare Jun 13 '13 at 19:25