This is the code of my sharedpreferences.It is working well in putting and retriving data but not able to clear data from sharedpreferences
SharedPreferences sharedPreferences1 = getSharedPreferences("userDataInSharedPref",MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences1.edit();
editor.putString("loginas", loginas_);
editor.putString("name", name_);
editor.putString("yearofbirth", yearofbirth_);
editor.putString("gender", gender_);
editor.apply();
SharedPreferences sharedPreferences1 = getContext().getApplicationContext().getSharedPreferences("userDataInSharedPref", Context.MODE_PRIVATE);
String uname = sharedPreferences1.getString("name", "");
String udob = sharedPreferences1.getString("yearofbirth", "");
String ugender = sharedPreferences1.getString("gender", "");
String uspeci = sharedPreferences1.getString("loginas", "");
UserName.setText(uname);
Birth_date.setText(udob);
Usergender.setText(ugender);
Specification.setText(uspeci);
binding.logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.clear();
editor.commit();
// SharedPreferences sharedPreferences = getActivity().getApplicationContext().getApplicationContext().getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
}
});
to clear one string :
sharedPreferences.edit().remove("name").commit();
to clear all strings :
sharedPreferences.edit().clear().apply();
Check if you are using any singleton class where you might be retrieving the values of these variables using SharedPreferences. The instance of this class need to be set to null too along with above solution.
To clear it you need to add this code
public void clear(){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
Related
fragment 1:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("name", "testnameJack");
editor.commit();
fragment 2:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String data= sPrefs.getString("name", "err");
emailId.setText(data);
I want transfer data to between two fragment but not working
Try:
SharedPreferences sPrefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String data= sPrefs.getString("name","No name defined");
emailId.setText(data);
This isn't how it works. If you update SharedPreferences while both fragments are on screen... how would they know that the preference had changed. There are two ways to solve this easily:
1) Add an OnSharedPreferenceChangeListener to the preferences in the fragment you are attempting to update. When the listener detects a change you can alter your text. In your case fragment 2. for example:
sPrefs.registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// .. Check the key to see if its the one you are looking for then set the text
}
});
Don't forget to unregister the listener to avoid leaks though.
2) Implement an interface in the parent Activity or Fragment and call a public method from the Activity in Fragment 2.
see docs
Good Luck and Happy Coding!
answer:
//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
//strVersionName->Any value to be stored
prefsEditor.putString("STOREDVALUE", strVersionName);
prefsEditor.commit();
//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String StoredValue=myPrefs.getString("STOREDVALUE", "");
Thanks everyone :)
I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file
SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor et = sp.edit();
et.putString("key",data);
et.apply();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
In second activity
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
desiredPreference = sharedPreferences.getString("key","data");
Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();
}
The Value is null because you used PreferenceManager.getDefaultSharedPreferences(this) which returns preference with this activity name and it's different from the other preference you used in your first activity. Instead, you should call your preference in the same way you called it in your first activity.
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String desiredPreference = sharedPreferences.getString("key","data");
To know more about the difference you can check the documentation and this answer.
Do something like this,
For storing
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", data);
editor.commit();
for Retriving
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String checkDate = sharedPref.getString("key","");
In my MainActivity I have a textView.
In that textView there is a Number that I keep in a SharedPreferences.
and every couple of min The SharedPreferences is changed with an alarm manager,
but the SharedPreferences in my MainActivity wont change,
anyone has an idea why?
this is a part of The code in the MainActivity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int ReleaseDate = preferences.getInt("com.fisher.freedom.ReleaseDate", 0);
TextView edit = (TextView) findViewById(R.id.DaysLeft);
Toast.makeText(MainActivity.this, "" + preferences.getInt("com.fisher.freedom.ReleaseDate", 0), Toast.LENGTH_SHORT).show();
edit.setText("" + ReleaseDate);
This is the code in the AlarmReceiver
public static final String ReleaseDate_Key = "com.fisher.freedom.ReleaseDate";
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
int ReleaseDate = preferences.getInt(ReleaseDate_Key, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(ReleaseDate_Key, --ReleaseDate);
editor.apply();
For get the value of your int use this:
SharedPreferences sharedPreferences = getSharedPreferences(getApplicationContext().getPackageName(),0);
int ReleaseDate = sharedPreferences.getInt("ReleaseDate",0);
And to save it use this:
SharedPreferences prefs = getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
prefs.edit().putInt("ReleaseDate", ReleaseDate).commit();
With this you forget about writing on static variable your package name, it worked for me, so it's going for you.
I am currently having some trouble getting a shared preference in another activity. I currently have the following set up in my main activity:
OnCreate method:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
Then I have a menu to edit the preference:
SharedPreferences.Editor editor = getPreferences(
MODE_PRIVATE).edit();
String value = input.getText().toString();
editor.putString("KEY", value);
editor.commit();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
However when I try to receive the data in another activity in its OnCreate method it doesn't get the data:
Second Activity:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String tut = preferences.getString("KEY", "");
ip = tut;
Any ideas?
instead of using "getPreferences(0)" you need to set and use shared preferences with his own name, this is an example:
//Fragment Activity One
SharedPreferences prefs = getActivity().getSharedPreferences("user",0);
SharedPreferences.Editor setPrefs = prefs.edit();
setPrefs.putString("name",profile.getName());
setPrefs.putString("email",profile.getEmail());
setPrefs.putString("idFacebook",profile.getIdFacebook());
setPrefs.putString("password",profile.getPassword());
setPrefs.putString("bio",profile.getBio());
setPrefs.putInt("id",profile.getId());
setPrefs.commit();
//Fragment Activity Two
SharedPreferences prefs = getActivity().getSharedPreferences("user",0);
String name = prefs.getString("name","")
thats how i use SharedPreferences, hope it help
You are using the private version of shared preferences; how you are using it, the values can only be seen by the originating Activity. You should be using getSharedPreferences(String, int); instead. Learn more at: http://developer.android.com/guide/topics/data/data-storage.html#pref
I have a configuration page which has a form on it. When the button is pressed, I want to save that value to a SharedPreference. This SharedPreference value then needs to be accessed from elsewhere in my app.
I am trying to save the value like the below. I want to save the collectionID so I can use it elsewhere
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
Button mButton;
EditText mEdit;
String collectionID;
String key = "GregKey";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, collectionID);
editor.commit();
}
});
}
}
Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. The example above crashes the application at the moment so something isn't quite right
I want to save the collectionID so I can use it elsewhere
Use mButton Button onClick event for saving EditText text in SharedPreferences as :
mButton.setOnClickListener( new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
// save value here in SharedPreferences
SharedPreferences settings =
ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, collectionID);
editor.commit();
}
});
Your crash occurs because your value is null:
String savedID;
You need to add a value to the variable:
String savedID = "somevalue";
Also, your key is null as long as the Button is not pressed which will also lead to a crash.
The putString(String key, String value) method enables you to store a specific value with a specific key, that can later be used to reaccess the stored value.
Example:
String key = "somekey";
String value = "yourvaluetostore";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();
In another Activity:
String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
// get the value "" is default
String value = sharedPreferences.getString(key, "");
All you need in the other Activity is the key you stored the value with. With this key, you can pull the correct stored value out of the SharedPreferences. --> The key is needed to identify the value.
Since you are using the part of code :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();
Log.d("Saved as", savedID);
in the onCreate method, that translates to
...
editor.putString(null, null);
Log.d("Saved as", null);
Correct your code so that you fill those elements before. I guess you wanted to make the save in the OnClick part
Yes something its not quite right here because as i see you are saving nothing. on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button mButton;
EditText mEdit;
String collectionID;
String savedID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(COLLECTIONID_KEY, collectionID);
editor.commit();
Log.d("Saved as", COLLECTIONID_KEY);
}
}
then to retrieve it :
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);
and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null!