在listview中第二次下載圖片時就會出現
SkAndroidCodec::NewFromStream returned null
可能是圖片大了點,它第一次還沒下載完就第二次開始調用了
所以我采取的措施就是:既然每次下載圖片都是在子線程中執行的,於是我在外面(循環里面)等待子線程調用完畢后再進行下一張圖片的下載
以下是我 部分中的 完整代碼
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();//初始化,simpleAdapter 需要綁定的數據是List<Map<String,Object>>類型的 for (int i = 0; i < bitmap.length; i++) { final Map<String, Object> item = new HashMap<String, Object>(); c.setvalue(i); //因為需要將i變量傳遞到線程中,就通過一個類的變量進行獲取 Thread t_ = new Thread(new Runnable() { @Override public void run() { String url="http://"+StaticValue.add_ip+":8089/images/"+image_url[ c.getvalue()]; //網絡URL bitmap[c.getvalue()] = getHttpBitmap(url); //或獲取URL轉bitmap的方法 savePicture(bitmap[c.getvalue()],image_url[ c.getvalue()]);//下載到本地 } }); t_.start(); try { t_.join(); //等待線程執行結束 } catch (InterruptedException e) { e.printStackTrace(); } FileInputStream fis = null; try { fis = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/M2_test/download/" + image_url[i]); //獲取剛剛子線程中存在本機的圖片 } catch (FileNotFoundException e) { e.printStackTrace(); } BitmapFactory.Options op = new BitmapFactory.Options(); op.inPreferredConfig = Bitmap.Config.RGB_565; op.inDither = true; op.inSampleSize = 10; op.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeStream(fis,null,op); item.put("pic", bitmap); item.put("mono", mono[c.getvalue()]); data.add(item); }
//simpleAdapter 默認不支持圖片的接受,所以需要重寫方法 SimpleAdapter adapter = new SimpleAdapter(getContext(), data ,R.layout.vlist, new String[]{"pic","mono"}, new int[]{R.id.im ,R.id.tv_mono}); adapter.setViewBinder(new SimpleAdapter.ViewBinder() { public boolean setViewValue(View view, Object attentionList, String textRepresentation) { if(view instanceof ImageView && attentionList instanceof Bitmap){ ImageView iv=(ImageView)view; iv.setImageBitmap((Bitmap) attentionList); return true; }else{ return false; } } }); lv.setAdapter(adapter);
public Bitmap getHttpBitmap(String url) { Bitmap bitmap = null; try { URL pictureUrl = new URL(url); InputStream in = pictureUrl.openStream(); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } public void savePicture(Bitmap bitmap,String pic_name) { String pictureName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/M2_test/download/" + pic_name; File file = new File(pictureName); FileOutputStream out; try { out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
以上就是我實現在listview實現查看網絡圖片的代碼
之前還遇到
Unable to decode stream: java.io.FileNotFoundException (No such file or directory)
我是通過
BitmapFactory.decodeFile( UrlString, options);
怎么檢查UrlString都能Logcat中顯示正確的路徑
所以我只能通過將網絡圖片下載到本機,通過獲取本機路徑顯示圖片