I have a problem with adding values in savedInstanceState
in Android. I tried to find solution on the internet, but I cannot seem to find a solution. Maybe some of you might know where the problem is. I need to put HashMap> to savedInstanceState
, and retrieve that onCreate method. Has anyone encountered and solved this problem?
Thank you for your time.
Asked
Active
Viewed 2,232 times
4

David Kariuki
- 1,522
- 1
- 15
- 30

marko kurt
- 205
- 4
- 12
2 Answers
9
you can use putSerializable. E.g.
savedInstanceState.putSerializable("KEY", hashMapInstance);

Blackbelt
- 156,034
- 29
- 297
- 305
-
and make sure your keys and values are serializable too. – alex Apr 13 '15 at 12:19
-
Integer, List and HashMap implement serializable, @dit – Blackbelt Apr 13 '15 at 12:20
-
op has no `MyCustomNoSerializableObject`. Op is using a `HashMap
>` @dit – Blackbelt Apr 13 '15 at 12:25 -
so I need to serialized keys and values, and this answers should work ? – marko kurt Apr 13 '15 at 12:33
-
which part is confusing you ? – Blackbelt Apr 13 '15 at 12:35
-
I put my HashMap in savedInstanteState, and the problem is when I want to save that hashmap in other variable. I have variable `private HashMap
> answers;` , and if my savedInstanceState is not empty, I want to put saved hash to answers. If I write `answers = savedInstanceState.getSerializable("KEY")`, it throws me error. Can you help me with saveing the saved state in new variable. Thank you – marko kurt Apr 13 '15 at 12:41 -
3you have to cast the return value of `getSerializable` to the specific type: `answers = (HashMap
>) savedInstanceState.getSerializable("KEY");`. Including the specific error would be useful tough – Blackbelt Apr 13 '15 at 12:45 -
Also User ArrayList. Other list classes do not serialize in Android. – mudit_sen Sep 03 '20 at 05:58
0
Try :
private HashMap<String, String> savedInstanceMap = new HashMap<>();
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
savedInstanceMap.put("selectedFuel_type_Id", selectedFuel_type_Id);
outState.putSerializable("savedBundle", savedInstanceMap);
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
savedInstanceMap = (HashMap<String, String>) savedInstanceState.getSerializable("savedBundle");
selectedFuel_type_Id = savedInstanceMap.get("selectedFuel_type_Id");
}

Mujahid Khan
- 1,712
- 1
- 18
- 24