How to read/write a boolean preference - android

Edit: this code actually works. I had problem in the code that used it. Leaving it anyway in case anybody will find it useful.
I have a class with two methods to write and read a boolean persisted preference. However, if I write a new value and then try to read it, I still get the old value. Only if I kill the app and relaunch it, I do get the new value. Any idea what the problem is?
Context mContext;
....
public void writeFlag(boolean flag) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putBoolean("mykey", flag);
editor.commit();
}
public boolean readFlag() {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getBoolean("mykey", false);
}

public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()

public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences =
getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ",
android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()

public class SharePref {
private static final String TAG = SharePref.class.getSimpleName();
private static SharePref mThis;
private Context mContext;
private SharedPreferences mPreference;
private SharePref() {
}
public static void init(Context context) {
if (mThis == null) {
mThis = new SharePref();
mThis.setData(context);
}
}
private void setData(Context context) {
mThis.mContext = context;
mPreference = mContext.getSharedPreferences(TAG, Context.MODE_PRIVATE);
}
public static SharePref getInstance() {
return mThis;
}
public void writeString(String tag, String data) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putString(tag, data).apply();
}
public String readString(String tag) {
if (mPreference == null)
mPreference = mContext.getSharedPreferences(TAG, Context.MODE_PRIVATE);
return mPreference.getString(tag, null);
}
public void writeBoolean(String tag, boolean data) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putBoolean(tag, data).apply();
}
public boolean readBoolean(String tag) {
return mPreference.getBoolean(tag, false);
}
public void clear(String tag) {
mPreference.edit().remove(tag).apply();
}
}
//In Activity
SharePref.init(this);
SharePref.getInstance().writeString("key","value");

Related

How do I make a shared library for SharedPreference?

I am working on an application that has a lot of modules in it, and I need to load data from a SharedPreference class that I made called SharedPrefManager in the :app application which is the application where I implement the other modules into a module called :mediplan where I just want to retrieve the ID that I saved in the SharedPrefManager.
I tried to implement the dependency in the module in question :mediplan but I ended up with a lot of errors so I went back and took off the dependency.
The SharedPrefManager class:
package com.example.tuteur;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "CIN";
private static final String IDCONT = "con";
private static final String malade = "malade";
private static SharedPrefManager mInstance;
private static Context ctx;
public SharedPrefManager(Context context) {
ctx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
public void setIdCont(String id) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(IDCONT, id);
editor.apply();
}
//this method will give the logged in user
public String getIdCont() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(IDCONT, null);
}
//this method will give the logged in user
public void setMalade(String malade) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(malade, malade);
editor.apply();
}
//this method will give the logged in user
public String getMalade() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(malade, null);
}
//this method will log the user out
public void logout() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}
the solution I found is to use put extras and put bundle instead of using the shared libraries

android static methods usage

I am developing an android application, In which I created one "SessionManager.java" which contains only static methods, in splash screen Activity only, I am creating the instance for "SessionManager ", Because it is the
fist activity in app, But in sometimes, I am getting null object reference ,
is it necessary to instantiate Class in every activity ?
Sample code
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public static void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified!");
}
public static void setMobile (String login_mobile) {
editor.putString("mobile", login_mobile);
editor.commit();
}
public static String getMobile() {
return pref.getString("mobile", "00");
}
}
sometimes in some activities , getMobile() method is returning null value, why ? can I check null value before return that ? please give me any suggestions, I stuck here.
If you are using it for storing values in shared preference then do it like this
public class AppSharedPreferences {
private SharedPreferences appSharedPrefs;
private SharedPreferences.Editor prefsEditor;
private static AppSharedPreferences appSharedPrefrence;
public AppSharedPreferences(Context context) {
this.appSharedPrefs = context.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public AppSharedPreferences() {
}
public static AppSharedPreferences getsharedprefInstance(Context con) {
if (appSharedPrefrence == null)
appSharedPrefrence = new AppSharedPreferences(con);
return appSharedPrefrence;
}
public SharedPreferences getAppSharedPrefs() {
return appSharedPrefs;
}
public void setAppSharedPrefs(SharedPreferences appSharedPrefs) {
this.appSharedPrefs = appSharedPrefs;
}
public SharedPreferences.Editor getPrefsEditor() {
return prefsEditor;
}
public void Commit() {
prefsEditor.commit();
}
public void clearallSharedPrefernce() {
prefsEditor.clear();
prefsEditor.commit();
}
public void setUserId(String userid)
{
this.prefsEditor=appSharedPrefs.edit();
prefsEditor.putString("user_id", userid);
prefsEditor.apply();
}
public String getUserId() {
return appSharedPrefs.getString("user_id","");
}
}
and then to use it in class do it like this way
appSharedPreferences=AppSharedPreferences.getsharedprefInstance(ActivityLogin.this);
and then call your method using appsharedPreferences.yourMethod();

How to retrive SharedPreferences, which where saved from another activity in Android?

I have situation in my app. Let's take two activities A & B . A is the main activity(which gets started when app is opened). B is started from A. I have a check box in B, who's boolean value using isChecked() method is assigned to a boolean called value & is saved to SharedPreferences. The code for saving to SharedPreferences is
SharedPreferences sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("value", value);
editor.commit();
Now I want to read this value from activity A(i.e the Main activity), during opening the app and depending on this value I need to perform additional operations.
The code I use to retrieve the value is
SharedPreferences sharedPreference=PreferenceManager.getDefaultSharedPreferences(this);
boolean value=sharedPreferences.getBoolean("value", false);
The problem is that I am not able to retrive this values in activity A.Since the value is not retrieved the operations depending on value are not carried out.Also no matter how many times I check the checkBox upon restarting the application CheckBox remain unchecked in activity B. What is the problem?
You can create singleton class that manage app's preferences (do not forget make your own YourAppSingleton class):
public final class PreferencesUtil {
private PreferencesUtil() {}
public static float getFloatValue(String key, float defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getFloat(key, defaultValue);
}
public static void setFloatValue(String key, float value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putFloat(key, value);
editor.commit();
}
public static long getLongValue(String key, long defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getLong(key, defaultValue);
}
public static void setLongValue(String key, long value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void setIntValue(String key, int value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static int getIntValue(String key, int defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getInt(key, defaultValue);
}
public static void setStringValue(String key, String value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringValue(String key) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getString(key, null);
}
public static String getStringValue(String key, String defValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getString(key, defValue);
}
public static boolean getBooleanValue(String key, boolean defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getBoolean(key, defaultValue);
}
public static void setBooleanValue(String key, boolean value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void clearValue(String key) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.remove(key);
editor.commit();
}
private static SharedPreferences getSharedPreferences() {
return YourAppSingleton.getInstance().getSharedPreferences(YourAppSingleton.getInstance().getString(R.string.app_name), Context.MODE_PRIVATE);
}
}
Application class:
public class YourAppSingleton extends Application {
private static YourAppSingleton instance = null;
public void onCreate() {
super.onCreate();
instance = this;
}
public static YourAppSingleton getInstance() {
return instance;
}
}

SharedPreferences cleared if remove the app from recent activity android

I'm using SharedPreferences in my project with MODE_PRIVATE, when i cleared the app from recent activity list, and opens the app again, all my preference data is cleared.
I'm using this class fro setting and getting preference.
public class Preferences {
private Context _context;
private SharedPreferences _preferences;
private Editor _editor;
private String prefName = "pref";
//=====
public Preferences(Context context){
_context = context;
_preferences = this._context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
_editor = this._preferences.edit();
}
//=====
public Preferences commit(){
_editor.commit();
return this;
}
//=====
public Preferences set(String key, String value){
_editor.putString(key, value);
return this;
}
//=====
public String get(String key){
return _preferences.getString(key, "");
}
//=====
public Preferences set(String key, int value){
_editor.putInt(key, value);
return this;
}
//=====
public int getInt(String key){
return _preferences.getInt(key, 0);
}
//=====
public Preferences setBoolean(String key, boolean value){
_editor.putBoolean(key, value);
return this;
}
//=====
public void removeKey(String key){
_editor.remove(key);
}
//=====
public boolean getBoolean(String key){
return _preferences.getBoolean(key, false);
}
}
can any one help me ...??
change your set method like this
public Preferences set(String key, int value){
_editor.putInt(key, value);
_editor.commit();
return this;
}
you don't need separate commit() into independent method.
good luck
this is another example, in this example i create a value that save my city name and when my app lunched i check for existing , if exist the value of that key returned to me.
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// define sp
sp=getSharedPreferences("test", Context.MODE_PRIVATE);
// get sp value if exist
if(sp.contains("EkbatanApp")){
String spResult=sp.getString("EkbatanApp", "");
}
}
//save key
public void SaveSettingOnClick(View v){
Editor editor=sp.edit();
editor.putString("EkbatanApp", "Borujerd");
editor.commit();
}

Using SharedPreferences across multiple classes?

I have a SharedPreferences that currently works in one class but doesn't work in a second class. I think I might be calling it wrong, because the error I get says:
The method getSharedPreferences(String, int) is undefined for the type CheckPreferences
The code that works correctly with the SharedPrefernces is this:
public void loadApp()
{
setContentView(shc_BalloonSat.namespace.R.layout.main);
alert = new AlertDialog.Builder(this).create();
//String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
//prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
prefEditor.commit();
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
CheckPreferences cp = new CheckPreferences(this, new CheckPreferences.CheckPreferencesListener()
{
public void onSettingsSaved()
{
// This function let's the activity know that the user has saved their preferences and
// that the rest of the app should be now be shown.
check.saveSettings();
}
public void onCancel()
{
Toast.makeText(getApplicationContext(), "Settings dialog cancelled", Toast.LENGTH_LONG).show();
}
});
cp.show();
}
In my other class, I don't know if I'm just calling it incorrectly or if I'm looking at it completely incorrectly. The class is shown below:
package shc_BalloonSat.namespace;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.CheckBox;
public class CheckPreferences extends Dialog
{
Context shc;
private CheckBox altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
private CheckBox latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
private CheckBox longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
private CheckBox velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
private CheckPreferencesListener listener;
SharedPreferences pref;
Editor prefEditor;
String userAltitudePreference;
String userLatitudePreference;
String userLongitudePreference;
String userVelocityPreference;
String userAltitudeChoice;
String userLatitudeChoice;
String userLongitudeChoice;
String userVelocityChoice;
public interface CheckPreferencesListener
{
public void onSettingsSaved();
public void onCancel();
}
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
this.setContentView(R.layout.custompreferences);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}
private void initOnClick()
{
View.OnClickListener click = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId())
{
case R.id.saveBtn:
{
saveSettings();
listener.onSettingsSaved();
dismiss();
break;
}
case R.id.cancelBtn:
{
listener.onCancel();
dismiss();
break;
}
}
}
};
// Save Button
this.findViewById(R.id.saveBtn).setOnClickListener(click);
// Cancel Button
this.findViewById(R.id.cancelBtn).setOnClickListener(click);
}
public void saveSettings()
{
// This function is called when the user chooses the save their preferences
if (altitudeCheckBox.isChecked())
{
userAltitudeChoice = "true";
prefEditor.putString(userAltitudePreference, userAltitudeChoice);
prefEditor.commit();
}
else if (latitudeCheckbox.isChecked())
{
userLatitudeChoice = "true";
prefEditor.putString(userLatitudePreference, userLatitudeChoice);
prefEditor.commit();
}
else if (longitudeCheckbox.isChecked())
{
userLongitudeChoice = "true";
prefEditor.putString(userLongitudePreference, userLongitudeChoice);
prefEditor.commit();
}
else if (velocityCheckbox.isChecked())
{
userVelocityChoice = "true";
prefEditor.putString(userVelocityPreference, userVelocityChoice);
prefEditor.commit();
}
else
{
}
}
}
The error I mentioned above occurs on this line:
pref = getSharedPreferences("shared_prefs", 1);
Any help will be greatly appreciated. I'd love to know what I'm doing wrong.
Ofcourse SharedPreferences is same across multiple classes. It allows you to save and retrieve persistent key-value pairs of primitive data types in your application.
Standard practice is to have one single Helper class with all static methods to save and retrieve key-value pairs of each type. Also, have all your keys in one static class SharedPreferenceKeys. It avoids silly typographical mistakes. Following is sample class which you can use:
package com.mobisys.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class HelperSharedPreferences {
public static class SharedPreferencesKeys{
public static final String key1="key1";
public static final String key2="key2";
}
public static void putSharedPreferencesInt(Context context, String key, int value){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putInt(key, value);
edit.commit();
}
public static void putSharedPreferencesBoolean(Context context, String key, boolean val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putBoolean(key, val);
edit.commit();
}
public static void putSharedPreferencesString(Context context, String key, String val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putString(key, val);
edit.commit();
}
public static void putSharedPreferencesFloat(Context context, String key, float val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putFloat(key, val);
edit.commit();
}
public static void putSharedPreferencesLong(Context context, String key, long val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putLong(key, val);
edit.commit();
}
public static long getSharedPreferencesLong(Context context, String key, long _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getLong(key, _default);
}
public static float getSharedPreferencesFloat(Context context, String key, float _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getFloat(key, _default);
}
public static String getSharedPreferencesString(Context context, String key, String _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, _default);
}
public static int getSharedPreferencesInt(Context context, String key, int _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, _default);
}
public static boolean getSharedPreferencesBoolean(Context context, String key, boolean _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, _default);
}
}
To put value (say boolean), call following from activity:
HelperSharedPreferences.putSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
To get same value, call following:
HelperSharedPreferences.getSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
Last value is default value.
You should have to call this method via context reference variable.
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
shc=context;
...
pref = shc.getSharedPreferences("shared_prefs", 1);
...
}
The Dialog class doesn't have a getSharedPreferences method defined. You probably want:
getContext().getSharedPreferences(...)

Categories

Resources