在 Bundle 中使用 Android HashMap?

android.os.Message使用 Bundle和它的 sendMessage 方法一起发送。因此,有没有可能把一个 HashMap放在一个 Bundle里面?

64478 次浏览

According to the doc, Hashmap implements Serializable, so you can putSerializable I guess. Did you try it ?

try as:

Bundle extras = new Bundle();
extras.putSerializable("HashMap",hashMap);
intent.putExtras(extras);

and in second Activity

Bundle bundle = this.getIntent().getExtras();


if(bundle != null) {
hashMap = bundle.getSerializable("HashMap");
}

because Hashmap by default implements Serializable so you can pass it using putSerializable in Bundle and get in other activity using getSerializable

If you want to send all the keys in the bundle, you can try

for(String key: map.keySet()){
bundle.putStringExtra(key, map.get(key));
}

Please note: If you are using a AppCompatActivity, you will have to call the protected void onSaveInstanceState(Bundle outState) {} (NOT public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {}) method.

Example code...

Store the map:

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("leftMaxima", leftMaxima);
outState.putSerializable("rightMaxima", rightMaxima);
}

And receive it in onCreate:

if (savedInstanceState != null) {
leftMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("leftMaxima");
rightMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("rightMaxima");
}

Sorry if it's some kind of a duplicate answer - maybe someone will find it useful. :)

  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;
}

I am using my kotlin implementation of Parcelable to achieve that and so far it works for me. It is useful if you want to avoid the heavy serializable.

Also in order for it to work, I recommend using it with these

Declaration

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)
}
}


}

Use

write

val map = LinkedHashMap<Int, String>()
val wrap = ParcelableMap<Int,String>(map)
Bundle().putParcelable("your_key", wrap)

read

val bundle = fragment.arguments ?: Bundle()
val wrap = bundle.getParcelable<ParcelableMap<Int,String>>("your_key")
val map = wrap.map

Don't forget that if your map K,V are not parceled by default they must implement Parcelable

In Kotlin:

hashMap = savedInstanceState?.getSerializable(ARG_HASH_MAP) as? HashMap<Int, ValueClass>


putSerializable(ARG_HASH_MAP, hashMap)