Null pointer exception when getting image from url to put in imageview

為{幸葍}努か 提交于 2019-12-11 19:45:50

问题


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)


来源:https://stackoverflow.com/questions/17095311/null-pointer-exception-when-getting-image-from-url-to-put-in-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!