我尝试使用Bitmap
和ImageView
下载并显示图片。
我使用的AsyncTask
以url
和view
作为参数,但我总是得到一个
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
doInBackground:
protected Bitmap doInBackground(Void... params) {
try {
Log.d("MyActivity", url.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
Bitmap res = BitmapFactory.decodeStream(is);
is.close();
if(res!= null)
Log.d("MyActivity", "I'm here");
return res;
} catch(IOException ioe){
}
return null;
}
onPostExecute:
protected void onPostExecute(Bitmap bitmap) {
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
if(bitmap == null)
Snackbar.make(view, "Error", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
else if(bitmap instanceof Bitmap) {
imageView.setImageBitmap(bitmap);
Snackbar.make(view, "Downloaded", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
答案 0 :(得分:0)
您传递给asynctask的视图不包含带有R.id.imageView id的ImageView,因此当您尝试在View中找到ImageView时,您将获得一个null ImageView。然后,当调用setImageBitmap方法时,由于ImageView == null,会得到nullPointerException。
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
if(null == imageView) {
Log.e("Error", "Ouh! there is no there is no child view with R.id.imageView ID within my parent view View.");
}
尝试上面的代码,您将看到在LogCat中打印错误。