Android开发:无法通过Intent传递HashMap问题求助
解决Intent传递Map<String, ApplicationInfo>时的方法找不到错误
你遇到的这个错误,本质是Android的Intent.putExtra()方法没有直接支持传递这种类型的Map集合。虽然ApplicationInfo本身实现了Parcelable接口,但普通的Map并没有被Intent的putExtra重载方法覆盖,所以编译器找不到匹配的方法。
下面给你两种可行的解决方案,优先推荐第一种,因为更简洁高效:
方案一:使用Bundle的putParcelableMap方法
因为ApplicationInfo是Parcelable的实现类,我们可以借助Bundle的putParcelableMap方法来传递这个Map,具体代码如下:
发送端代码
Map<String, ApplicationInfo> map = returnedMap; Intent i = new Intent(LoadingScreen.this, DisplayClass.class); i.putExtra("total", total); // 创建Bundle并放入Parcelable类型的Map Bundle bundle = new Bundle(); bundle.putParcelableMap("map", (Map<String, ? extends Parcelable>) map); i.putExtras(bundle); startActivity(i);
接收端代码
// 从Intent中取出Bundle Bundle bundle = getIntent().getExtras(); if (bundle != null) { int total = bundle.getInt("total"); // 获取传递的Map Map<String, ApplicationInfo> map = bundle.getParcelableMap("map"); }
方案二:将Map转换为Parcelable对象列表(兼容更多场景)
如果第一种方案在某些特殊版本或场景下有问题,可以把Map的键值对封装成自定义的Parcelable对象,再传递ArrayList:
1. 定义Parcelable的键值对类
public class AppInfoPair implements Parcelable { private String key; private ApplicationInfo appInfo; public AppInfoPair(String key, ApplicationInfo appInfo) { this.key = key; this.appInfo = appInfo; } // 从Parcel中读取数据的构造方法 protected AppInfoPair(Parcel in) { key = in.readString(); appInfo = in.readParcelable(ApplicationInfo.class.getClassLoader()); } // Parcelable必需的Creator public static final Creator<AppInfoPair> CREATOR = new Creator<AppInfoPair>() { @Override public AppInfoPair createFromParcel(Parcel in) { return new AppInfoPair(in); } @Override public AppInfoPair[] newArray(int size) { return new AppInfoPair[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(key); dest.writeParcelable(appInfo, flags); } // Getter方法 public String getKey() { return key; } public ApplicationInfo getAppInfo() { return appInfo; } }
2. 发送端代码
Map<String, ApplicationInfo> map = returnedMap; Intent i = new Intent(LoadingScreen.this, DisplayClass.class); i.putExtra("total", total); // 将Map转换为ArrayList<AppInfoPair> ArrayList<AppInfoPair> appPairs = new ArrayList<>(); for (Map.Entry<String, ApplicationInfo> entry : map.entrySet()) { appPairs.add(new AppInfoPair(entry.getKey(), entry.getValue())); } i.putParcelableArrayListExtra("appPairs", appPairs); startActivity(i);
3. 接收端代码
int total = getIntent().getIntExtra("total", 0); ArrayList<AppInfoPair> appPairs = getIntent().getParcelableArrayListExtra("appPairs"); // 将ArrayList转换回Map Map<String, ApplicationInfo> map = new HashMap<>(); if (appPairs != null) { for (AppInfoPair pair : appPairs) { map.put(pair.getKey(), pair.getAppInfo()); } }
另外补充一点:你也可以把Map转换成HashMap(因为HashMap实现了Serializable),然后用putExtra(String, Serializable)来传递,但这种方式依赖Java的序列化机制,效率比Parcelable低,所以不推荐在Android中使用。
内容的提问来源于stack exchange,提问作者federicosancho
相关产品推荐
相关产品推荐

