save arraylist in shared preference

后端 未结 5 1257
抹茶落季
抹茶落季 2020-12-06 15:32

I am storing values in ArrayList and pass it to using bundle to next Fragment, and there I set values to my TextView, till here it wor

5条回答
  •  星月不相逢
    2020-12-06 16:27

    First download Gson.jar from below link and then add it to libs folder of your project

    http://www.java2s.com/Code/Jar/g/Downloadgson17jar.htm

    then put That ArrayList in the Class and make object of that class then you can save that object to SharedPreferences like below

    public static void save_User_To_Shared_Prefs(Context context, User _USER) {
        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context.getApplicationContext());
        SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(_USER);
        prefsEditor.putString("user", json);
        prefsEditor.commit();
    
     }
    

    above code is an example _USER objext contain ArrayList.

    And to read the object have a look at below code

     public static User get_User_From_Shared_Prefs(Context context) {
    
        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context.getApplicationContext());
        Gson gson = new Gson();
        String json = appSharedPrefs.getString("user", "");
    
    
        User user = gson.fromJson(json, User.class);
        return user;
    } 
    

    now when you want to get the _USER object call the above function and in result you will have the object and in that you will have the ArrayList

提交回复
热议问题