Bundle是一種利用鍵值對存儲的數據格式,而我們在程序中通常利用HashMap存儲數據。在開發中,通過Http請求得到JSONArray類型的返回值,我選擇利用ArrayList<HashMap<String, String>>格式存儲JSONArray對象。Bundle對象中putParcelabelArrayList方法可以將ArrayList格式數據傳入Bundle,用於Intent在不同activity中傳遞。因此需要一種將ArrayList<HashMap<String, String>>格式轉為ArrayList<Bundle>格式的方法。
下面就貼出我實現的方法:
1 /** 2 * ArrayList中存儲的Hashmap轉為bundle 3 * @param list 4 * @return 5 */ 6 public static ArrayList<Bundle> Map2Bundle(ArrayList<HashMap<String, String>> list){ 7 ArrayList<Bundle> bundleList = new ArrayList<>(); 8 for(HashMap map : list) { 9 Bundle bundle = new Bundle(); 10 Iterator iter = map.entrySet().iterator(); 11 while (iter.hasNext()) { 12 Map.Entry entry = (Map.Entry)iter.next(); 13 Object key = entry.getKey(); 14 Object value = entry.getValue(); 15 bundle.putString(String.valueOf(key), String.valueOf(value)); 16 } 17 bundleList.add(bundle); 18 } 19 return bundleList; 20 }
這里遍歷HashMap時采用的是效率最高的迭代器。歡迎大家多多批評指正!