I try call SharedPreferences, and I pass a parameters but not work (not update and not put data)
I don't know I do wrong?
public void put(String value){
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
editor.putString("isFirstRunCheck", value);
editor.commit();
}
public void checkFirstRun3(){
SharedPreferences prefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
String name ="";
if (restoredText != null) {
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
}
if(name.equals("true")){
Toast.makeText(getActivity(), "click si ", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "click no ", Toast.LENGTH_SHORT).show();
}
}
I put my "put()" I do not see it work
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
cbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
}
});
I'm not sure why you don't think this is working, but I'm guessing it is because your code doesn't do what you think it does.
First of all, the comment on this line is wrong:
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
The second parameter to getString() is the default value- in this case you are specify that the default value should be an empty string if you have not previously saved a value to the "isFirstRunCheck" key.
Second, you seem to be expecting a value of "si". However, you are only ever calling put("true") and put("false")- you never call put("si"), so your conditional in checkFirstRun3() will always be false.
As an aside, a String is an odd way to save boolean data. SharedPreferences has a getBoolean() and a putBoolean() that will likely suit your needs better.
Try to change
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
to
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor spe = sp.edit();
Use
spe.putString("yourStringKey", yourStringValue).commit()
and then get your data using the "yourStringKey"
and don't forget to call your put(someData) method.
Related
I've created a class to save some username and password using the Android SharedPreferences, its seems that the methods for set both username and password are ok.
But everytime i try to get these, from within another activity or by just trying to print out the value i receiver nothing (if trying to print the value) or null (if trying to get on i activity).
Here is my code:
public class AuthPreferences {
private static final String KEY_USER = "userid";
private static final String KEY_PASSWORD = "mypassword";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
Log.v("MailApp", "User is " + user);
editor.apply();
if(editor.commit() == true) {
System.out.println("The user was set!");
}else{
System.out.println("The user was not set!");
}
}
public void setPassword(String pass) {
Editor editor = preferences.edit();
editor.putString(KEY_PASSWORD, pass);
Log.v("MailApp", "Password is " + pass);
editor.apply();
if(editor.commit() == true) {
System.out.println("The password was set!");
String mainUser = preferences.getString(KEY_PASSWORD, "456");
System.out.println(mainUser);
}else{
System.out.println("The password was not set!");
}
}
public String getUser() {
return preferences.getString(KEY_USER, "456");
}
public String getPassword() {
return preferences.getString(KEY_PASSWORD, "456");
}
Here is how i'm trying to get it:
preferences = new AuthPreferences(getActivity());
try {
String mainUser = preferences.getUser();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("App", "Could not get the user");
}
It is all because you use Activity as a context (you use result of getActivity() method as context). Since you got different activities you got different contexts so in result you are accessing different shared preferences files (XMLs). In other words you are writing to file A in activity A, and then read in activity B using file B as your source. This obviously is not going to work. To have this all work as you expect you shall always use the same context for data that you want to be accessed across many activities, in this case I recommend to use Application context. Technically, instead of calling getActivity() to get context in your fragment, you call getActivity().getApplicationContext() to get your application context, so you will be accessing the same shared preferences storage file, not matter what activity or fragment is doing that write or read.
Aside from this there's no need to call apply() and commit() as these two is kinda equivalent and do the same. Please check docs for more information.
Try replacing:
Editor editor = preferences.edit();
with
SharedPreferences.Editor editor = preferences.edit();
Then replace editor.apply(); with editor.commit();.
Instead of doing:
editor.apply();
do this:
editor.commit();
Also you need to commit your edits by using the methods somewhere:
AuthPreferences preferences = new AuthPreferences(getActivity());
preferences.setUser("USER_NAME");
preferences.setPassword("PASSWORD_VALUE");
Got this code, which basicly updates my textviews depending on how far the user is in the quiz, which is stored in sharedPrefs. But when the correct answer is entered the prefs doesn't update. Does the commit() need too long time to set the prefs, so the activity calls the method setText() before the sharedPrefs are updated or what am i doing wrong?
private void setText() {
SharedPreferences score = this.getSharedPreferences("football", MODE_PRIVATE);
questionNumber = score.getInt("football", 0);
question.setText(questions.get(questionNumber).get(0));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCheckAnswer:
if (questions.get(questionNumber).contains(etAnswer.getText().toString())) {
Integer newQ = questionNumber += 1;
SharedPreferences change = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = change.edit();
editor.putInt("football", newQ);
editor.commit();
setText();
}else{
question.setText("error occured");
}
break;
}
You're not opening the SharedPreference the same way when setting and getting.
Change this:
SharedPreferences change = this.getPreferences(Context.MODE_PRIVATE);
to this:
SharedPreferences change = this.getSharedPreferences("football", MODE_PRIVATE);
Notice the differences:
getPreferences vs getSharedPreferences
you didn't give the preference reference as "football"
Are you sure the prefs doesn't get updated or is it just that your textview isn't getting updated? If this is being done in your Activity, you should not be changing layout (your text view) from within the Activity. You should use a Handler to make UI changes.
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();
}
}
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 have in preferences.xml following EditTextPreference:
<EditTextPreference
android:name="#string/pref_test"
android:defaultValue="0.6"
android:inputType="numberDecimal"
android:key="editTestPref"
android:maxLength="5"
android:summary=""
android:title="#string/pref_test" />
In one of my activities I read the value.
But the problem is if the user enters nothing (""), my app crashes. Sure I could do a if statement in the activity to check if its empty string, but I want to do following:
In Preferences.java I get changes of the preferenceEditText. There I want to set a default value if the user enters "":
if (preference.getKey().equals("editTestPref")) {
if(newValue.equals(""))
{
final SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("editTestPref", "1");
prefsEditor.commit();
summary = "0.6"; // to update the summary of preference
}
else
{
summary= (String) newValue;
}
}
I also tried this code:
SharedPreferences customSharedPreference = getSharedPreferences(
"myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference
.edit();
editor.putString("editTestPref", "1");
editor.commit();
Both do not work, they do not update the sharedPreference value. It is still "".
Implement SharedPreferences.OnSharedPreferenceChangeListener like so:
public class YourPrefsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
// ... your existing code ...
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set up a listener whenever a key changes
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ("editTestPref".equals(key)) {
String val = sharedPreferences.getString("editTestPref", "");
if (val == null || val.trim().equals("")) {
val = "0.6"; // <-- your default value
sharedPreferences.edit().putString(key, val).commit();
}
}
}
}
The method is called when the user changed the preferences value, and checks if he entered an empty string. If so, the value is replaced by your default value.
You should rather use if(newValue.isEmpty()) instead of checking the characters
i dont see anything wrong in your code but try this if it works..
Replace this
prefsEditor.putString("editTestPref", "1");
with
prefsEditor.putString("editTestPref", String.valueof(1));
Best Luck.