我对此很陌生。现在这个简单的应用程序从网络下载图像作为可绘制图像,然后将其转换为位图(将其存储在缓存中)并在 UI 中显示。当我运行它时,它会给出NullPointerException。
代码:-
public class ImageActivity extends Activity {
/** Called when the activity is first created. */
private LruCache<String, Bitmap> mchache;
ImageView imageview;
Bitmap image;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageview=(ImageView)findViewById(R.id.img);
Log.i("shu","HERE @ calling loadimage");
loadimage();
}
public void loadimage()
{ Log.i("shu","HERE @ inside ");
image = (Bitmap) mchache.get("img");
Log.i("shu","HERE @line1passed");
if (image==null)
{ Log.i("shu","HERE @ imahe==null");
downloadimage();
}
else if (image != null)
{ Log.i("shu","HERE @ image!= null");
imageview.setImageBitmap(image);
}
}
// converts drawable to bitmap
public static Bitmap drawableToBitmap (Drawable drawable) {
Log.i("shu","HERE @ drawable to bitmap");
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public void downloadimage()
{ Log.i("shu","HERE @ download image");
String address="http://abd.com/absde.jpg";
try{
URL url = new URL(address);
InputStream content = (InputStream)url.getContent();
Drawable d = Drawable.createFromStream(content , "src");
imageview.setImageDrawable(d);
Bitmap bmap = drawableToBitmap(d);
mchache.put("img",bmap);
}
catch (IOException e)
{ Log.i("shu","HERE @ exception");
}
}
}
现在根据logcat,问题出在这里
image = (Bitmap) mchache.get("img");
代码黑白两个日志信息,所以任何人都可以指出是什么原因造成的。我在支持库的帮助下使用 LRUCache,因为它在 api8 中不存在。