问题描述
- imageView获取图片空指针异常
-
通过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); } }
}
解决方案
写法没问题,只不过thumbnail不应该在外部去查找指向他的id
ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail);
改成:
ImageView thumbnail即可
解决方案二:
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
new DownloadImageTask()
.execute("http://imgstatic.baidu.com/img/image/shouye/liushishi1.jpg");
}
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
@Override
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;
}
}
这样写没发现什么问题,你那写法有问题
时间: 2024-09-20 03:51:41