We made a simple clicker game and I wanted to save the highscores in the SharedPreferences. So we wrote this code in MainActivity:
SharedPreferences sharedPref = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("Highscore",clicks);
editor.commit();
int clicks is the score you made that round.
In another activity, we wanted to display the Highscore in a TextView:
SharedPreferences sharedPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
highscore = sharedPrefs.getInt("Highscore",0);
highscoretv.setText(Integer.toString(highscore));
But the highscore wasn't displayed. Have you an idea what I can do??????
Maybe try to replace Context.MODE_PRIVATE to just MODE_PRIVATE in both activities
You should use this piece of code instead of Context.MODE_PRIVATE
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Instead of using editor.commit(); , you should use editor.apply();
Apply will update the preference object instantly and will save the new values asynchronously.
Sorry guys. I solved it by myself. The Highscore was displayed in the Launcher Activity that was already open in the background. So as I closed the MainActivity, the LauncherActivity got in Foreground, but didn't update. Can you tell me if theres a thing like onActivityinForeground so I can prevent this?
Related
How can I add a signup and login activity to my existing project using shared preferences?
I already changed AndroidManifest.xml and set the loginActivity to be LAUNCHER activity.
my main problem is that I don't know how to write and work with shared preferences.
Please get acquainted with - https://developer.android.com/training/data-storage/shared-preferences
It is MUST-TO-KNOW basics :)
It is very simple
To set signed user use:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("USERNAME_KEY", userName);
editor.apply();
And to get it use:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int highScore = sharedPref.getInt("USERNAME_KEY", "Unknown");
But SP - is not the best solution for authentication!
I'm working on a service in my app. I'm using some global variables values while running service in background when app destroy manually. But when i'm closing app, all variables become destroy.
How can I use these variables while app destroyed.
Any advise is highly appreciated.
Thanks
You can use Shared preferences. They are accessible across your application any time anywhere
First save the values before destroying the app.
SharedPreferences prefs= context.getSharedPreferences("MyValues", 0);
SharedPreferences.Editor saveValue = prefs.edit();
saveValue.putString("Key", "Value");
saveValue.commit();
Now you can get those values from any where.
SharedPreferences prefs= context.getSharedPreferences("MyValues", 0);
prefs.getString("key", "defaultValue");
When the App close your variables die, Use SharedPreferences if you want save and read smallthings!
for read:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int showed = sharedPref.getInt("var", 0);
for write:
SharedPreferences sharedPre2f = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPre2f.edit();
editor.putInt("var", 0);
editor.commit();
hy, everyone
i'm searching for a few days a solution for one problem i tried to search but i didn' find an answer for my problem so i decided to ask you maybe someone it will so kind and wil explaine to me ho can solve my problem.
So i have two activities, a configure one and a main one, my problem is that when i check one checkbox in the configure activity (i succeed to save the checkbox state so when i check it will be checked even if i leave the configure activity), but i don't know how can i use the checkbx state in the main activity. i found many suggestions but for for me nothing worked.
thank you in advance.
thank you for all for the answers but i not succeeded in this way to solve my problem, and with your suggestions i did the following: in the second activity(where i have the CheckBox): i have one Save function where i save with SharedPreferences the Checkbox State( even if i close the activity or anything else the state of Checkbox it's keeping his state) and i have made a Load function where when i load back the activity it's loading the previous state so inside this activity i thing it is ok, But in this case how can use the load function's value (in fact the checkbox value) int the MainActivity.
I'm sorry for inconvenience but i'm knew but i would like to learn.
Thank you ones again.
Store the value in SharedPreference to get the value of checkbox
chkIos.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString("checkboxState",((CheckBox) v).isChecked());
editor.commit();
//Save the state of checkbox in sharedPreference
}
}
});
In main activity get the state like this.
SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
String stateValue = sharedPreferences.getString("checkboxState);
i guess the sharepreferences will resolve that
SharedPreferences.Editor editor = app_preferences.edit();
editor.putBoolean("Checkbox", value);
editor.commit();
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
boolean value = app_preferences.getBoolean("Checkbox", false);
You can use SharedPreferences to save the state of your CheckBox in the device so you can retrieve it from another Activity.
Here is an example how to use them. Also you can check this YouTube video that shows you how to make preferences screen for your Activities.
I am using a service to download and retrieve a list of URL's and put them in a sharedpreference.
With this..
SharedPreference images_article = this.getSharedPreferences("images_articles", MODE_WORLD_READABLE);
editor.putString("article2", urlImage2);
editor.putString("article3", urlImage2);
editor.commit();
Then in my Main.Activity i pull the url's from preference.
SharedPreference images_article = this.getSharedPreferences("images_articles", MODE_WORLD_READABLE);
urlImage2 = images_article.getString("article2", "NO ARTICLE AVAILABLE");
urlImage3 = images_article.getString("article3", "NO ARTICLE URL AVAILABLE");
The only problem is for some reason it isnt going inside of the shared preference, because the Main activity is loading the OLD URL's that has now changed. But in the Service i log the url's being retrieved and they are updated but for some reason in the main activity it still loads the old one. and im retrieving them from the same preference.
Is there anything i am missing or a better way to do this? Any help would be great!!
I was running in to a similar issue with my SharedPreferences between my Activity and Service. I ended up not using the default and used my own set file name
in the activity and service I set
private static final String PREFERENCE_NAME = "MyPreferenceFileName";
Then to get the values:
SharedPreferences pref = getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
pref_checked = pref.getBoolean("checked", true);
and to set the values:
SharedPreferences pref = getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("checked", value);
editor.commit();
This allowed me to use the same get and put logic in both my Service and Activity without any issues. I hope this helped.
This might be happening due to the different contexts you are accessing from. I am not very sure though, but you can try this :
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
Use this code, whenever you try to access SharedPreferences, that is, from both the Service and the Activity. That might solve your problem.
Using this in both the Activity and Service classes seems to work for me, as it should now be using the same Context to access the application SharedPreferences:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
I have stored the username and the password in the sharedpreference.
And I am displaying the username in every activity like Welcome "Username".
But at the time of logout I have put one checkbox in the dialog box.If the check box is checked the sharedpreference value should be clear. So I don't know how to do it.Please help me out of it. Thank you.
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
if (settings.contains("mykey")) {
SharedPreferences.Editor editor = settings.edit();
editor.remove("mykey");
editor.apply();
}
The method to clear the sharedpreferences is this
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear()
With this you dont delete the xml
Editor.clear();
Editor.commit();
You have to use remove method which is simple and described here. The only parameter is the Key you have used to save this preference.
1st method
Your_sharedprefrence_name..clear();
Your_sharedprefrence_name.commit();
2nd Method
Your_sharedprefrence_name.clear().commit();
3rd Method(When u want to clear the arraylist of sharedprefrence put it in loop)
Your_sharedprefrence_name.remove(String.valueOf(i)).clear().commit();