Android HashMap in Bundle?
尝试为:
1 2 3 | Bundle extras = new Bundle(); extras.putSerializable("HashMap",hashMap); intent.putExtras(extras); |
和第二个活动
1 2 3 4 5 | Bundle bundle = this.getIntent().getExtras(); if(bundle != null) { hashMap = bundle.getSerializable("HashMap"); } |
因为默认情况下Hashmap实现
进行其他活动
根据该文档,
请注意:如果您使用的是AppCompatActivity,则必须调用
示例代码...
存储地图:
1 2 3 4 5 6 | @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("leftMaxima", leftMaxima); outState.putSerializable("rightMaxima", rightMaxima); } |
并在onCreate中接收它:
1 2 3 4 | if (savedInstanceState != null) { leftMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("leftMaxima"); rightMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("rightMaxima"); } |
很抱歉,如果答案重复,也许有人会觉得有用。 :)
如果要发送分发包中的所有密钥,可以尝试
1 2 3 | for(String key: map.keySet()){ bundle.putStringExtra(key, map.get(key)); } |
我正在使用我的Parcelable的kotlin实现来实现这一目标,到目前为止,它对我来说仍然有效。
如果要避免大量的可序列化,这将很有用。
也为了使其正常工作,我建议将它们与这些
一起使用
声明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class ParcelableMap<K,V>(val map: MutableMap<K,V>) : Parcelable { constructor(parcel: Parcel) : this(parcel.readMap(LinkedHashMap<K,V>())) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeMap(map) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ParcelableMap<Any?,Any?>> { @JvmStatic override fun createFromParcel(parcel: Parcel): ParcelableMap<Any?,Any?> { return ParcelableMap(parcel) } @JvmStatic override fun newArray(size: Int): Array<ParcelableMap<Any?,Any?>?> { return arrayOfNulls(size) } } } |
使用
写
1 2 3 | val map = LinkedHashMap<Int, String>() val wrap = ParcelableMap<Int,String>(map) Bundle().putParcelable("your_key", wrap) |
阅读
1 2 3 | val bundle = fragment.arguments ?: Bundle() val wrap = bundle.getParcelable<ParcelableMap<Int,String>>("your_key") val map = wrap.map |
别忘了,如果默认情况下未打包地图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public static Bundle mapToBundle(Map<String, Object> data) throws Exception { Bundle bundle = new Bundle(); for (Map.Entry<String, Object> entry : data.entrySet()) { if (entry.getValue() instanceof String) bundle.putString(entry.getKey(), (String) entry.getValue()); else if (entry.getValue() instanceof Double) { bundle.putDouble(entry.getKey(), ((Double) entry.getValue())); } else if (entry.getValue() instanceof Integer) { bundle.putInt(entry.getKey(), (Integer) entry.getValue()); } else if (entry.getValue() instanceof Float) { bundle.putFloat(entry.getKey(), ((Float) entry.getValue())); } } return bundle; } |
在Kotlin:
1 2 3 | hashMap = savedInstanceState?.getSerializable(ARG_HASH_MAP) as? HashMap<Int, ValueClass> putSerializable(ARG_HASH_MAP, hashMap) |