How to save an instance of a custom class in onSaveInstanceState?

前端 未结 5 1981
臣服心动
臣服心动 2020-12-02 12:33

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 12:52

    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.

提交回复
热议问题