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();
Related
In my current app I made a set of passpoints and want there to be an option to delete them from a different activity. I saw a few questions similar to this on stackoverflow and tried to follow their instructions and tinker a little but nothing worked. What is wrong with my code?
First Activity: ( the activity with the preferences i'm trying to delete )
public void setDefaults() {
SharedPreferences mPrefs = getSharedPreferences(RESETT_PASSPOINTS, 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(RESETT_PASSPOINTS,Identifier);
editor.commit();
}
Second Activity : ( the activity i'm trying to delete from )
public void deleteDefaults(){
SharedPreferences mPrefs = getSharedPreferences(Activity1.RESETT_PASSPOINTS, 0);
String str = mPrefs.getString(Activity1.RESETT_PASSPOINTS, Activity1.Identifier);
if (str.equals(Activity1.Identifier)){
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
}
}
Also, I know I could use the intents ".put extra" way of doing it but I don't want to start the activity i'm deleting from
Try replacing:
if (str.equals(Activity1.Identifier)){
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
}
For this:
if (str.equals(Activity1.Identifier)){
SharedPreferences.Editor editor = mPrefs.edit();
editor.remove(Activity1.RESETT_PASSPOINTS).commit();
}
Hope it helps!
public void updateDefaults(){
SharedPreferences mPrefs = getSharedPreferences(RESETT_PASSPOINTS, 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(RESETT_PASSPOINTS,"OTHER_VALUE");
editor.commit();
}
Best option for you is to update it and check its value again.
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
I am developing an android application which should authenticate user only once in his mobile after installing the app. It should not ask the details for the second time. For this I have used shared preferences by setting a Boolean value. But it,s not working. Is there any suggestions here.. thanks friends !! My code is here
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("Register", true);
editor.commit();
use it this way :
in your onCreate() use :
if (isFirstTime()) {
// do what you want to do only once
}
to call the below :
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
Your approach of using SharedPreference is correct.Put the below coad snippet in your oncreate() method of the Activity.
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
register = prefs.getBoolean("Register",false);
if(!register)
{
//register user
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("Register", register);
editor.commit();
}
else{
//continue with the rest
}
the first time :
settings.edit().putBoolean("Register", true).commit();
and in onCreate you do the test
if(!settings.getBoolean("Register",false))
//it isn't the first time
So the full code :
SharedPreferences settings = getSharedPreferences("settings", 0);
if(!settings.getBoolean("Register",false)){
//it isn't the first time
}
else{
settings.edit().putBoolean("Register", true).commit();
}
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();