无法通过意图传递Hashmap

问题描述 投票:0回答:3

我正在尝试将Hashmap传递给另一个意图,但我收到错误:

Cannot resolve method 'putExtra(java.lang.String,java.util.Map<String,android.content.pm.ApplicationInfo>

码:

Map<String, ApplicationInfo> map = returnedMap;
Intent i = new Intent(LoadingScreen.this, DisplayClass.class);
i.putExtra("total",total);
i.putExtra("map", map);
startActivity(i);
java android android-intent
3个回答
0
投票

Intent.putExtra只接受原始类型/ ParcelableSerializable对象。

因为你持有Map,所以很容易将它作为HashMap发送,因为HashMap实现了Serializable接口。

// If your originial Map is not a HashMap, you have to convert it
// HashMap<String, ApplicationInfo> map = new HashMap<>(returnedMap);
// If it's already an HashMap, you have to cast it
// HashMap<String, ApplicationInfo> map = (HashMap)returnedMap;
i.putExtra("map", map);

在接收方:

HashMap<String, ApplicationInfo> map = (HashMap<>)intent.getSerializableExtra("map")

0
投票

你需要创建一个HashMap原因HashMap是实现Serializable的类。 Mapinterface的父母HashMap

HashMap<String, ApplicationInfo> map = returnedMap;
Intent i = new Intent(LoadingScreen.this, DisplayClass.class);
i.putExtra("total",total);
i.putExtra("map", map);
startActivity(i);

0
投票

由于HashMaps序列化而地图没有,因此请尝试执行以下段,因为您正在使用

Intent.putExtra(String,Serializable)方法:

HashMap<String, ApplicationInfo> hashMap = returnedMap;
© www.soinside.com 2019 - 2024. All rights reserved.