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时采用的是效率最高的迭代器。欢迎大家多多批评指正!