user1841702 user1841702 - 2 months ago 17x
Android Question

Android - LinkedHashMap cannot be passed between Activities

I have a very strange problem. All I want to do is pass a

(I am just experimenting here and the I would like the choice of data structure to remain unchanged regardless of performance overhead) object from one Activity to another via an
. I tried two approaches after initializing and populating my data structure:

LinkedHashMap<String,HashMap<String,String>> mData = new LinkedHashMap<String,HashMap<String,String>>();
//insert data into LinkedHashMap

Approach 1:

Intent intent = new Intent(this, TestActivity.class);
// as a Serializable

Approach 2:

Intent intent = new Intent(this, TestActivity.class);
Bundle bundle = new Bundle();

And in the receiving Activity:

For Approach 1:

Intent intent = getIntent();
mData = (LinkedHashMap<String, HashMap<String, String>>) intent.getSerializableExtra("DATA");

For Approach 2:

Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("DATA");
mData = (LinkedHashMap<String, HashMap<String, String>>) bundle.getSerializable("LIST");

And I keep running into this issue:

Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.LinkedHashMap
at com.matchify.TestActivity.onCreate(
            at android.os.Handler.dispatchMessage(
            at android.os.Looper.loop(
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(
            at dalvik.system.NativeStart.main(Native Method)

What am I doing wrong ? Apologies if I have missed something very obvious.

Kai Kai

I checked LinkedHashMap's source code and found the data structure that stores iteration order is declared as transient:

transient LinkedEntry<K, V> header;

So even if LinkedHashMap is returned to the new Activity, the map would be broken as far as iteration is concerned, which may be the reason why HashMap is returned instead.

If you don't need guaranteed iteration order, just cast it as HashMap in the 2nd Activity, otherwise you may have to write your own Parcelable to preserve the ordering.