我通过网址获取图片并尝试将其设置为我的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);
}
}
}
答案 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)