Skip to content

Instantly share code, notes, and snippets.

@ImanX
Last active June 25, 2020 03:53
Show Gist options
  • Save ImanX/5e53aa9d95cf0b1221c881c939e87219 to your computer and use it in GitHub Desktop.
Save ImanX/5e53aa9d95cf0b1221c881c939e87219 to your computer and use it in GitHub Desktop.
public class Activity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SingletonSharePrefrences.getInstance().putString("KEY_NAME" , "MACK");
}
}
import android.app.Application;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
SingletonSharePrefrences.init(this, "PERSON_STORE");
}
}
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
public class SingletonSharePrefrences {
private static SingletonSharePrefrences instance;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public synchronized static void init(Context context, String name) {
instance = new SingletonSharePrefrences(context, name);
}
public static SingletonSharePrefrences getInstance() {
if (instance == null)
throw new IllegalStateException("You must to call init() before use getInstance()");
return instance;
}
@SuppressLint("CommitPrefEdits")
private SingletonSharePrefrences(Context context, String name) {
sharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void putString(String key, String value) {
editor.putString(key, value).commit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment