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);
        }
    }

}

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

But I need that globally so I can use it in the asynchtask
Great this fixed it! Can't accept your answer, have to wait 10 min
@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: square.github.io/picasso

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.