I created an instance of a custom class RestaurantList to hold my data (a list of restaurant data received from a web service as json data).
How can I save it in
Custom class objects can be converted to JSON and stored in the bundle as a string. The following example is for Fragments.
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Gson gson = new Gson();
String json= gson.toJson(customClass);
outState.putString("CUSTOM_CLASS", json);
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null) {
String json= savedInstanceState.getString("CUSTOM_CLASS");
if(!json.isEmpty()) {
Gson gson = new Gson();
CustomClass customClass = gson.fromJson(json, CustomClass.class);
}
}
}
For Activities, override onRestoreInstanceState method instead.