Search code examples
javaandroidandroid-intentpropertiesclasscastexception

How to pass Properties object from an intent to another?


I have this piece of code in Activity A:

Properties properties = new Properties();

/** Fill up properties here */

Intent intent = new Intent(this,Another.class);
intent.putExtra("prop",properties);
startActivity(intent);

Now..I try grant that extra from the Activity B (through Intent's Bundle) by:

Properties properties = (Properties) bundle.getSerializable("prop");

But I getting java.lang.ClassCastException followed by that message:

java.lang.RuntimeException: Unable to start activity ComponentInfo{gr.kanellis.sqlify/gr.kanellis.sqlify.activities.DatabaseView}: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Properties

And pointing the line that I cast the Properties object in Activity B.

I can't figure out how to solve this problem. Any help will be much appreciated.


Solution

  • Try this:

    Properties properties = new Properties();
    prop.setProperty("Hello", "Hi!");
    /*...*/
    Bundle bundle = new Bundle();
    bundle.putExtra("prop", properties);
    

    Then in your activity you can get it back, but you must cast it as a HashMap:

    Intent intent = this.getIntent();
    Bundle bundle = intent.getExtras();
    HashMap<String,String> map= (HashMap<String, String>)bundle.getSerializable("prop");
    map.get("Hello")
    

    The reason why this works it's completely explained in this solution and as a summary it's because Properties implements Map, and any class that implements Map that you put into a Bundle will come out as a HashMap.

    If you still need an object of type Property you can do this:

    Properties properties = new Properties();
    properties.putAll(map);