2

I want to pass a TreeMap through an Intent from one activity to another one. But somehow Android converts it into a HashMap on its way.

In a newly created project with two blank activities, running MainActivity in the emulator produces a java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.TreeMap.

First activity:

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import java.util.TreeMap;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent i = new Intent(this, SecondActivity.class);
        i.putExtra("map", new TreeMap<Long, Long>());
        //TreeMap<Long, Long> m = (TreeMap<Long, Long>) i.getSerializableExtra("map");
        startActivity(i);
    }

}

Second activity:

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import java.util.TreeMap;


public class SecondActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        TreeMap<Long, Long> m = (TreeMap<Long, Long>) getIntent().getSerializableExtra("map");
    }

}

Strangely enough, the commented code in the first activity runs without any problem.

TheGuy
  • 31
  • 5
  • 1
    This seems to answer your question. http://stackoverflow.com/questions/12300886/linkedlist-put-into-intent-extra-gets-recast-to-arraylist-when-retrieving-in-nex/12305459#12305459 – Paul Boddington Mar 18 '15 at 21:31

1 Answers1

1

As mentioned by pbabcdefp in his comment above, the cause of the problem is described here. A more detailed explanation can be found in this blog post.

An easy to implement solution to it is using Gson.

Community
  • 1
  • 1
TheGuy
  • 31
  • 5