从url获取图像以放入imageview时出现空指针异常

时间:2013-06-13 19:20:42

标签: android android-asynctask nullpointerexception android-imageview

我通过网址获取图片并尝试将其设置为我的imageView。但是我得到了一个空指针异常。它甚至没有进入我的asynchtask。

有什么我做错了或没有看到的吗?

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 个答案:

答案 0 :(得分:3)

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

您需要在充气布局后获取图片,否则findViewById将返回null

ImageView thumbnail; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail);
    thumbnail = (ImageView) findViewById(R.id.btnThumbnail)