How do you save/store objects in SharedPreferences on Android?

后端 未结 20 2624
野趣味
野趣味 2020-11-22 13:35

I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?

<
20条回答
  •  执笔经年
    2020-11-22 14:24

    If you want to store the whole Object that you get in response, It can achieve by doing something like,

    First Create a method that converts your JSON into a string in your util class as below.

     public static  T fromJson(String jsonString, Class theClass) {
        return new Gson().fromJson(jsonString, theClass);
    }
    

    Then In Shared Preferences Class Do something like,

     public void storeLoginResponse(yourResponseClass objName) {
    
        String loginJSON = UtilClass.toJson(customer);
        if (!TextUtils.isEmpty(customerJSON)) {
            editor.putString(AppConst.PREF_CUSTOMER, customerJSON);
            editor.commit();
        }
    }
    

    and then create a method for getPreferences

    public Customer getCustomerDetails() {
        String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null);
        if (!TextUtils.isEmpty(customerDetail)) {
            return GSONConverter.fromJson(customerDetail, Customer.class);
        } else {
            return new Customer();
        }
    }
    

    Then Just call the First method when you get response and second when you need to get data from share preferences like

    String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();
    

    that's all.

    Hope it will help you.

    Happy Coding();

提交回复
热议问题