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?
<If your Object is complex I'd suggest to Serialize/XML/JSON it and save those contents to the SD card. You can find additional info on how to save to external storage here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
To add to @MuhammadAamirALi's answer, you can use Gson to save and retrieve a list of objects
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();
String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null);
Type type = new TypeToken < List < Connection >> () {}.getType();
List < Connection > connections = new Gson().fromJson(connectionsJSONString, type);
Better is to Make a global Constants
class to save key or variables to fetch or save data.
To save data call this method to save data from every where.
public static void saveData(Context con, String variable, String data)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
prefs.edit().putString(variable, data).commit();
}
Use it to get data.
public static String getData(Context con, String variable, String defaultValue)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
String data = prefs.getString(variable, defaultValue);
return data;
}
and a method something like this will do the trick
public static User getUserInfo(Context con)
{
String id = getData(con, Constants.USER_ID, null);
String name = getData(con, Constants.USER_NAME, null);
if(id != null && name != null)
{
User user = new User(); //Hope you will have a user Object.
user.setId(id);
user.setName(name);
//Here set other credentials.
return user;
}
else
return null;
}
You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson
Or add the GSON dependency in your Gradle file:
implementation 'com.google.code.gson:gson:2.8.5'
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);
Try this best way :
PreferenceConnector.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferenceConnector {
public static final String PREF_NAME = "ENUMERATOR_PREFERENCES";
public static final String PREF_NAME_REMEMBER = "ENUMERATOR_REMEMBER";
public static final int MODE = Context.MODE_PRIVATE;
public static final String name = "name";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
Write the Value :
PreferenceConnector.writeString(this, PreferenceConnector.name,"Girish");
And Get value using :
String name= PreferenceConnector.readString(this, PreferenceConnector.name, "");
Here's a take on using Kotlin Delegated Properties that I picked up from here, but expanded on and allows for a simple mechanism for getting/setting SharedPreference properties.
For String
, Int
, Long
, Float
or Boolean
, it uses the standard SharePreference getter(s) and setter(s). However, for all other data classes, it uses GSON to serialize to a String
, for the setter. Then deserializes to the data object, for the getter.
Similar to other solutions, this requires adding GSON as a dependency in your gradle file:
implementation 'com.google.code.gson:gson:2.8.6'
Here's an example of a simple data class that we would want to be able to save and store to SharedPreferences:
data class User(val first: String, val last: String)
Here is the one class that implements the property delegates:
object UserPreferenceProperty : PreferenceProperty<User>(
key = "USER_OBJECT",
defaultValue = User(first = "Jane", last = "Doe"),
clazz = User::class.java)
object NullableUserPreferenceProperty : NullablePreferenceProperty<User?, User>(
key = "NULLABLE_USER_OBJECT",
defaultValue = null,
clazz = User::class.java)
object FirstTimeUser : PreferenceProperty<Boolean>(
key = "FIRST_TIME_USER",
defaultValue = false,
clazz = Boolean::class.java
)
sealed class PreferenceProperty<T : Any>(key: String,
defaultValue: T,
clazz: Class<T>) : NullablePreferenceProperty<T, T>(key, defaultValue, clazz)
@Suppress("UNCHECKED_CAST")
sealed class NullablePreferenceProperty<T : Any?, U : Any>(private val key: String,
private val defaultValue: T,
private val clazz: Class<U>) : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T = HandstandApplication.appContext().getPreferences()
.run {
when {
clazz.isAssignableFrom(String::class.java) -> getString(key, defaultValue as String?) as T
clazz.isAssignableFrom(Int::class.java) -> getInt(key, defaultValue as Int) as T
clazz.isAssignableFrom(Long::class.java) -> getLong(key, defaultValue as Long) as T
clazz.isAssignableFrom(Float::class.java) -> getFloat(key, defaultValue as Float) as T
clazz.isAssignableFrom(Boolean::class.java) -> getBoolean(key, defaultValue as Boolean) as T
else -> getObject(key, defaultValue, clazz)
}
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = HandstandApplication.appContext().getPreferences()
.edit()
.apply {
when {
clazz.isAssignableFrom(String::class.java) -> putString(key, value as String?) as T
clazz.isAssignableFrom(Int::class.java) -> putInt(key, value as Int) as T
clazz.isAssignableFrom(Long::class.java) -> putLong(key, value as Long) as T
clazz.isAssignableFrom(Float::class.java) -> putFloat(key, value as Float) as T
clazz.isAssignableFrom(Boolean::class.java) -> putBoolean(key, value as Boolean) as T
else -> putObject(key, value)
}
}
.apply()
private fun Context.getPreferences(): SharedPreferences = getSharedPreferences(APP_PREF_NAME, Context.MODE_PRIVATE)
private fun <T, U> SharedPreferences.getObject(key: String, defValue: T, clazz: Class<U>): T =
Gson().fromJson(getString(key, null), clazz) as T ?: defValue
private fun <T> SharedPreferences.Editor.putObject(key: String, value: T) = putString(key, Gson().toJson(value))
companion object {
private const val APP_PREF_NAME = "APP_PREF"
}
}
Note: you shouldn't need to update anything in the sealed class
. The delegated properties are the Object/Singletons UserPreferenceProperty
, NullableUserPreferenceProperty
and FirstTimeUser
.
To setup a new data object for saving/getting from SharedPreferences, it's now as easy as adding four lines:
object NewPreferenceProperty : PreferenceProperty<String>(
key = "NEW_PROPERTY",
defaultValue = "",
clazz = String::class.java)
Finally, you can read/write values to SharedPreferences by just using the by
keyword:
private var user: User by UserPreferenceProperty
private var nullableUser: User? by NullableUserPreferenceProperty
private var isFirstTimeUser: Boolean by
Log.d("TAG", user) // outputs the `defaultValue` for User the first time
user = User(first = "John", last = "Doe") // saves this User to the Shared Preferences
Log.d("TAG", user) // outputs the newly retrieved User (John Doe) from Shared Preferences