Null pointer exception when getting image from url

2019-08-29 03:04发布

问题:

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:

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)