I am trying to save some data in shared preferences on Android and as the following page says (http://developer.android.com/guide/topics/data/data-storage.html#pref), I should write some code like the code shown bellow inside onCreate() method:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tablet);
//Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
The problem is that the last line:
setSilent(silent);
gives an error shown as:
The method setSilent(boolean) is undefined for the type MainActivity
What should I do to solve this?
Thank you!
To save a value in using sharedpreferences:
SharedPreferences pref = this.getSharedPreferences("Test",0);
Editor editor = pref.edit();
editor.putString("VALUE", value);
editor.commit();
And get it like that:
SharedPreferences prfs = getSharedPreferences("Test", Context.MODE_PRIVATE);
String v= prfs.getString("VALUE", "");
Remove the following line:
setSilent(silent);
The value you need has already been stored in the variable silent. The above line was presumably included to demonstrate what you can do with the variable
To get stored value using SharedPreference
private String getOnPreference() {
String prefName = null;
try {
SharedPreferences myPrefs2 = this.getSharedPreferences("myPrefs",
MODE_PRIVATE);
prefName = myPrefs2.getString("key",value);
} catch (Exception e) {
LOG.error("Get error in shared preference", e);
}
return prefName;
}
To set value using Shared preference
private void setOnPreference(String value) {
try {
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("key", value);
prefsEditor.commit();
} catch (Exception e) {
LOG.error("Set error in shared preference", e);
}
}
Simply use the above functions to get and set any data using shared preference
Related
I am trying to delete the data from shared preferences. But I cant do that. To track that the data is removed or not, I am using this code:
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(share_pref_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(share_pref_file);
editor.clear();
editor.commit();
getApplicationContext().getSharedPreferences(share_pref_file, 0).edit().clear().commit();
String strJson = prefs.getString("jsondata","");
if(strJson != null)
{
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
But in logcat window it is showing me "cccccccccccccccccccccccccccc" value every time.
So can anyone help me out that how to remove/delete the data from shared preferences so that if I click on 'logout' button it will remove all the stored data? Thanks in advance.
An empty string is still a string (and String("") != null will return true). Try this instead:
if(!strJson.equals(""))
This assumes the empty string will never be a valid input in your SharedPreferences in the first place.
Try this one inside the button click event to clear the SharedPreferences values.
Editor editor = getSharedPreferences("MyPref", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Try editor.clear(); followed by a editor.commit();
Here is one example that I've used:
Preference clearPref = (Preference) findPreference("MyPref");
btnLogout.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
Toast.makeText(getBaseContext(), "All data cleared!", Toast.LENGTH_SHORT).show();
return true;
}
});
Either change this:
String strJson = prefs.getString("jsondata", "");
To:
String strJson = prefs.getString("jsondata", null);
And then check:
if(strJson != null) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
Or keep it as it is and check it like this:
if(strJson.equals("")) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
settings.edit().clear().commit();
is a one line code I am using, works perfectly
It is my solution:
You can put null instead of your favorite data in shareprefrences
getApplicationContext();
SharedPreferences.Editor pref = (Editor) getSharedPreferences("data", MODE_PRIVATE).edit();
pref.putString("admin_no", null);
pref.commit();
I want to run AsyncTask in android only once when application starts for the first time.
I tried to put Shared preference in onCreate but it didn't work. Any other ideas ?
SharedPreferences prefscrt = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefscrt.getBoolean("firstTime", false)) {
Log.d("DownloadManager", "Installing First Time");
new Task().execute(); //THIS WON'T WORK
SharedPreferences.Editor editor = prefscrt.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Thanks in advance
Madz
Try this code :
SharedPreferences prefs = getSharedPreferences("firstTime", MODE_PRIVATE);
registartion = prefs.getBoolean("firstTime", false);
and now put your if condition
1.First check the value is null or not if null then sharedpref use and save them..
2.But in second time again check if they have already sharedpref run your code .
private Boolean firstTime = null;
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
private boolean isFirstTime() {
if(firstTime == null) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
new Task().execute();
if (firstTime!=null) {
}
}
return firstTime;
}
What I'm trying to do
Hello Guys.
I got a Service which, set's a boolean to true or to false whenever the service is started or stopped (started = true / stopped = false) in the SharedPreference. Now when I try to get the Boolean out there in my Activity, it allways dosn't find it. How can I solve this... Here's the Code for you Guys.
Code
Methode in my Service:
private void setStarted(boolean started) {
// SharedPreferences casten
mPrefs = this.getSharedPreferences(LOG_TAG, MODE_PRIVATE);
// Boolean in SharedPreferences hinzufügen
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear().apply();
editor.putBoolean(PREF_STARTED, started).commit();
editor.commit();
//mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
Log.d(LOG_TAG, "Variabel " + mPrefs.getBoolean(PREF_STARTED, false));
}
In my Activity
// mPrefs caten
mPrefs = this.getSharedPreferences(GPSService.LOG_TAG, MODE_PRIVATE);
// boolean holen ob service gestartet oder nicht
run = mPrefs.getBoolean(GPSService.PREF_STARTED, false);
How do I get the boolean out of there? It allways returns me the default value I had to give in the getBoolean Methode.
Thanks for your help in advance
safari
Here is some code that I'm successfully using in one of my apps. It is used in various parts of the app, e.g. both from activities and services:
void putValue(Context context, String pref, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(pref, value);
editor.commit();
}
boolean getValue(Context context, String value, boolean defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
return settings.getBoolean(value, defaultValue);
}
Try using getDefaultSharedPreferences(Context context) method of PreferenceManager in both your services and your activities.
private void setStarted(boolean started) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
Log.d(LOG_TAG, "Variabel " + mPrefs.getBoolean(PREF_STARTED, false));
}
In your Activity
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
run = mPrefs.getBoolean(GPSService.PREF_STARTED, false);
Also make sure you :
Never call .clear() on editor.
You use PreferenceManager.getDefaultSharedPreferences(this) everywhere.
Just build your prefs object the same way you would as part of your activity. The only difference is pulling your application's context in.
SharedPreferences prefs = _ getApplicationContext().getSharedPreferences("com.example.appname", Activity.MODE_PRIVATE);
Boolean tmpBool = prefs.getBoolean("PREF_NAME", null);
I have made a program code for shared preference in android. But i am confused with sharedpreference. I am updating the sharedpreference if its not the same as earlier but every time i get the same value when i retrieve its value. Also please let me knw how to delete sharedpreference on onDestroy().
Bundle bundle = this.getIntent().getExtras();
resid=bundle.getString("locid");
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
String prefresid = app_preferences.getString("preflocid", null);
Log.i("pref res id is",""+prefresid);
if(prefresid!=null)
{
if(resid.equalsIgnoreCase(prefresid))
{
Log.i("preference res id is the same","");
}
else
{
SharedPreferences.Editor e = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
Log.i("preference res id is not same","creating new");
//SharedPreferences settings = getSharedPreferences("myfile", 0);
// SharedPreferences.Editor editor = settings.edit();
e.putString("preflocid",resid);
e.commit();
}
}
else
{
Log.i("new preference res id created",""+prefresid);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("preflocid", resid);
editor.commit();
Log.i("new preference res id created","");
}
What you are doing in your code will only change the value of the preference once, namely the first time you read it. The first time it is null, which means you go into the else and save "locid" to "preflocid". The next time "locid" is set to and you will go into the if and then into the first if because "locid".equalsIgnoreCase(prefresid).
To remove preferences in onDestroy, just call this:
#Override
protected void onDestroy() {
SharedPreferences.Editor e = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
e.clear();
e.commit();
}
Have just one object of default SharedPreference and have editor onto that like:
SharedPreferences s_pref= PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=s_pref.edit();
now you will have to use this editor directly wherever it is required.
I have created an activity where i have used shared preferences for storing data..now in another activity i have an reset button..when i click on the reset button the data store will be lost..so how that can be done..my code is
code in activity1:
public void writeToRegister()
{
// Write history data to register
SharedPreferences preferences1 = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor1 = preferences1.edit();
editor1.putInt("iHistcount", CycleManager.getSingletonObject().iHistCount);
for(int i=0;i< CycleManager.getSingletonObject().iHistCount;i++)
{
editor1.putLong("dtHistoryDate"+Integer.toString(i), CycleManager.getSingletonObject().dtHistory[i].getTime());
}
editor1.commit();
}
public void readFromRegister()
{
// Read history data from register
SharedPreferences preferences1 = getPreferences(MODE_PRIVATE);
CycleManager.getSingletonObject().iHistCount=preferences1.getInt("iHistcount", 0);
for(int i=0;i< CycleManager.getSingletonObject().iHistCount;i++)
{
Long x=preferences1.getLong("dtHistoryDate"+Integer.toString(i), 0L);
CycleManager.getSingletonObject().dtHistory[i]=new Date(x);
}
}
code for Activity 2:
Button pBtnReset = new Button(this);
pBtnNextMonth.setOnClickListener(pBtnReset OnClickListener);
Button.OnClickListener pBtnReset OnClickListenernew Button.OnClickListener()
{
public void onClick(View arg0)
{
}
};
so what i have to write in second activity reset button so that it clear the stored data
Get your Editor and call clear() something like this:
Edit: as the user DDoSAttack mentioned.
There are two ways of getting SharedPreferences
1: getting default SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
2: getting specific SharedPreferences
SharedPreferences prefs = Context.getSharedPreferences("FileName", Context.MODE_PRIVATE);
and here is how you'll clear it.
public void clear()
{
SharedPreferences prefs; // here you get your prefrences by either of two methods
Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
its very easy..
yourEditor.remove(" thing you want to remove on start");
and then give must
yourEditor.commit();
If you want to wipe all the data in a preference file call clear() from the SharedPreferences.Editor instance
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear()
Use SharedPreferences.Editor clear() method.
See Documentation
SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();