0

我通过 URL 获取我的图像并尝试将其设置为我的 imageView。但我得到一个空指针异常。它甚至没有进入我的异步任务。

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

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

}
4

1 回答 1

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)
于 2013-06-13T19:22:04.707 回答