Search code examples
androidandroid-activity

Pass HashMap<Integer, JSONObject> via intent as extra


I tried to pass an HashMap via intent from fragment to activity, but without success. this is my code:

    private HashMap<Integer, JSONObject> myData;

    Intent intent = new Intent(this.getActivity(),MyActivity.class);
    intent.putExtra("myMap", myData);
    startActivity(intent);

and I got a runtimeExeption:

    java.lang.RuntimeException: Parcel: unable to marshal value

I would be happy if someone can help me with that! I need a way to resolve it, I know that JSONObject is not Serializable. The value is not a custom object, therfore I can't implement Serializable there. Thank a lot!


Solution

  • Instead of

    HashMap<Integer, JSONObject> myData
    

    you should use

    HashMap<Integer, String> myData
    

    And add the items as Strings instead of JSONObject:

    myData.put(0, myJsonObject.toString());
    

    then, on your second activity, you create the JSON when needed:

    new JSONObject(myData.get(0));
    

    The reason:

    JSONObject is not serializable by default but String is (notice it implements Serializable).