🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / Android RMOS / sharedpreferences android save object class

1-) sharedpreferences android save object class

 

 

Save List of user-defined objects to SharedPreferences
    
public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS";
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();

    User entity =
new User();
// ... set entity fields

    
List<Connection> connections = entity.getConnections();
// convert java object to JSON format,
// and returned as JSON formatted string
    
String connectionsJSONString = new Gson().toJson(connections);
    editor.putString(KEY_CONNECTIONS, connectionsJSONString);
    editor.commit();
    Get List of user-defined objects from SharedPreferences
    String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS,
null);
    Type type =
new TypeToken < List < Connection >> () {}.getType();
    List < Connection > connections =
new Gson().fromJson(connectionsJSONString, type);

 

DİĞER

 

implementation 'com.google.code.gson:gson:2.8.8'
    
you can find latest version here

    Creating
a shared preference:

    SharedPreferences  
mPrefs = getPreferences(MODE_PRIVATE);
    To
save:

    MyObject
myObject = new MyObject;
//set variables of 'myObject', etc.

    
Editor prefsEditor = mPrefs.edit();
    Gson
gson = new Gson();
    
String json = gson.toJson(myObject);
    
prefsEditor.putString("MyObject", json);
    
prefsEditor.commit();
    To
retrieve:

    Gson
gson = new Gson();
    
String json = mPrefs.getString("MyObject", "");
    MyObject
obj = gson.fromJson(json, MyObject.class);

 

 

kaynak : https://stackoverflow.com/questions/7145606/how-do-you-save-store-objects-in-sharedpreferences-on-android

 

 

 

 2021 Aralık 29 Çarşamba
 405