how to reset all stored data store using shared preferences - android

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();

Related

SharedPreferences doesn't work android

I have a sharedPreferences object and SharedPreferencesEdit object but doesn't save anything
public void getPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("us1_Name", us1_Name.getText().toString());
spEditor.commit();
}
public void setPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
us1_Name.setText(sp.getString("us1_Name", "DEFAULT"));
}
I call this methods when onStop and onResume call, but doesn't work for me.
You just need to exchange your preference methods from your getPreferences() to setPreferences() like
public void getPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
us1_Name.setText(sp.getString("us1_Name", "DEFAULT"));
}
public void setPreferences(){
SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("us1_Name", us1_Name.getText().toString());
spEditor.commit();
}
in your getPreferences() you need to get saved preferences value by using
sp.getString("us1_Name", "DEFAULT")
in your setPreferences() you need to saved preferences value by using
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putString("us1_Name", us1_Name.getText().toString());
spEditor.commit();
first thing is that
1.) don't do any operations like sharedPreferance Edit / Database edit in onStop(); method
because it just call just for moment and it is only for do minor operation regarding activity
so please change it and do it in onPause();

Remove shared prefrences Android

On click of a button i want to remove the data that i have store on Login Activity.I have to remove this from diffrent activity how can we delete this .
This is how i have saved the values.
public void saveInformation(String username, String password) {
SharedPreferences shared = getSharedPreferences("SelfTrip", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
}
You can remove all entries from your shared preferences file with the following:
getSharedPreferences("SelfTrip",Context.MODE_PRIVATE).edit().clear().commit();
Try this
public void onClick(View arg0) {
SharedPreferences myPrefs = getSharedPreferences("SelfTrip",
MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();
finish();
}
And this is how you can delete values from the SharedPreferences:
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
Editor e = preferences.edit();
e.remove("yourkey");
e.commit();
Simply use the remove() method of the Editor and remove a value with your key.
To remove a value from SharedPreferences use the remove() method with the appropriate key (e.g. username):
SharedPreferences shared = getSharedPreferences("SelfTrip", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.remove("username").commit();

Android SharedPreferences update does not work

I know, this issue has been dealt with in many threads, but I cannot figure out this one.
So I set a shared preference like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.apply();
I read the preferences like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = null;
spinnerValuesSet = prefs.getStringSet(spinnerName,null );
Everything works, except for my changes are visible while this activity runs i.e. - I display the values from the SharedPreferences, allow the user to delete or add and then update the ListView. This works, but after I restart the application, I get the initial values.
This for example is my method to delete one value from the list, update the values in SharedPreferences and update the ListView
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
for (String s : spinnerValuesSet)
{
if(s == currentSelectedItemString)
{
spinnerValuesSet.remove(s);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, spinnerValuesSet );
editor.apply();
break;
}
}
updateListValues();
}
});
And this is the method that updates the ListView:
private void updateListValues()
{
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
if(spinnerValuesSet.size() > 0)
{
names = new ArrayList<String>();
names.clear();
int k=0;
for (String s : spinnerValuesSet) {
names.add(k, s);
k++;
}
namesAA = new ArrayAdapter<String> ( this, android.R.layout.simple_list_item_activated_1, names );
myList.setAdapter(namesAA);
}
}
Any help is much appreciated.
The Objects returned by the various get methods of SharedPreferences should be treated as immutable. See SharedPreferences Class Overview for reference.
You must call remove(String) through the SharedPreferences.Editor returned by SharedPreferences.edit() rather than directly on the Set returned by SharedPreferences.getStringSet(String, Set<String>).
You will need to construct a new Set of Strings containing the updated content each time since you have to remove the Set entry from SharedPreferences when you want to update its content.
Problem happens because the Set returned by SharedPreference is immutable. https://code.google.com/p/android/issues/detail?id=27801
I solved this by created a new instance of Set and storing in all the values returned from SharedPreferences.
//Set<String> address_ids = ids from Shared Preferences...
//Create a new instance and store everything there.
Set<String> all_address_ids = new HashSet<String>();
all_address_ids.addAll(address_ids);
Now use the new instance to push the update back to SharedPreferences
I may be wrong but I think the way you are retrieving the Shared Preferences is the problem. Try using
SharedPreferences prefs = getSharedPreferences("appPreferenceKey", Context.Mode_Private);
Use editor.commit(); instead of editor.apply();
Example Code:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.commit();
I hope this helps.
Depending on the OS Build you may have to save values in a different way.
boolean apply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
public static void saveValue(SharedPreferences.Editor editor)
{
if(apply) {
editor.apply();
} else {
editor.commit();
}
}

Delete data from shared preferences in android

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();

sharedpreference handling

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.

Categories

Resources