Android SharedPreferences Singleton Example
An example of SharedPreferences Singleton class in Android.
Java
public class SharePref {
private static SharePref sharePref = new SharePref();
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
private static final String PLACE_OBJ = "place_obj";
private SharePref() {} //prevent creating multiple instances by making the constructor private
//The context passed into the getInstance should be application level context.
public static SharePref getInstance(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
return sharePref;
}
public void savePlaceObj(String placeObjStr) {
editor.putString(PLACE_OBJ, placeObjStr);
editor.commit();
}
public String getPlaceObj() {
return sharedPreferences.getString(PLACE_OBJ, "");
}
public void removePlaceObj() {
editor.remove(PLACE_OBJ);
editor.commit();
}
public void clearAll() {
editor.clear();
editor.commit();
}
}
Kotlin
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
class SharedPref private constructor() {
companion object {
private val sharePref = SharedPref()
private lateinit var sharedPreferences: SharedPreferences
private val PLACE_OBJ = "place_obj"
fun getInstance(context: Context): SharedPref {
if (!::sharedPreferences.isInitialized) {
synchronized(SharedPref::class.java) {
if (!::sharedPreferences.isInitialized) {
sharedPreferences = context.getSharedPreferences(context.packageName, Activity.MODE_PRIVATE)
}
}
}
return sharePref
}
}
val placeObj: String
get() = sharedPreferences.getString(PLACE_OBJ, "")
fun savePlaceObj(placeObjStr: String) {
sharedPreferences.edit()
.putString(PLACE_OBJ, placeObjStr)
.apply()
}
fun removePlaceObj() {
sharedPreferences.edit().remove(PLACE_OBJ).apply()
}
fun clearAll() {
sharedPreferences.edit().clear().apply()
}
}
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts