在全球定义中,我已经宣布:private HashMap<String, Bitmap> map = new HashMap<String, Bitmap>();
在我的代码的其他部分,我连接到服务器并获取我需要的信息。其中两个是图像地址(url)和图像id。之后,我下载图像,我想为它分配自己的Id。这是我的代码:
private LinkedList<Bitmap> getFlagImages() {
InputStream is= null;
LinkedList<Bitmap> llBitmap = new LinkedList<Bitmap>();
for(int i = 0; i < flag.getTeamLogo44x44().size(); i++) {
String urlstr = flag.getTeamLogo44x44().get(i);
try {
HttpGet httpRequest = new HttpGet(urlstr);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
is = bufHttpEntity.getContent();
Bitmap bm = BitmapFactory.decodeStream(is);
llBitmap.add(bm);
map.put(flag.getTeamId().get(i), bm); // *Crash happens here
}catch ( MalformedURLException e ){
Log.d( "RemoteImageHandler", "Invalid URL passed" + urlstr );
}catch ( IOException e ){
Log.d( "RemoteImageHandler", "fetchImage IO exception: " + e );
}finally{
if(is != null) {
try{
is.close();
} catch(IOException e) {}
}
}
}
return llBitmap;
}
当我运行时,应用程序崩溃,logcat显示Null Pointer Exception并指向行map.put(flag.getTeamId().get(i), bm);
任何建议将不胜感激。
//更新,我也使用map.put(flag.getTeamId().get(i), Bitmap.createBitmap(bm));
但结果是一样的。
看起来像flag.getTeamId()
是null,或者像cheeken说的那样,flag.getTeamId.get(i)
是null
您可以尝试使用assert(flag.getTeamId()!= null)assert(flag.getTeamId()。get(i)!= null)等断言
现在用-ea标志运行你的jvm(启用断言的简称)
我变了
map.put(flag.getTeamId().get(i), bm);
至
map.put(flag.getTeamId().get(i), Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight()));
现在好了。但我不知道为什么第一个不起作用!
看起来你找到了答案。但是,您可以考虑让地图将WeakReference<Bitmap>
作为值。那是,
Map<Integer, WeakReference<Bitmap>>
通过保留弱引用,您可以确保垃圾收集在以后按预期工作。