I am trying to update the values of SharedPreferences, here is my code:
edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putString(Settings.PREF_USERNAME+"",txtuser);
edit.putString(Settings.PREF_PASSWORD+"",txtpass);
edit.commit();"
The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.
But when I am confirming the data in XML file ,the data updated in that.
And after restarting my application I am getting that updated values. So it requires me to restart the application to get updated values.
So, how to get those updated values once it changes?
Thanks in advance
Here is my whole code:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
ctx=this;
status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// get old value
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
on(ctx,true);// function will call and value is updated
}
}});
status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// this should give me a updated value but gives old value
}
public static boolean on(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Settings.PREF_ON, Settings.DEFAULT_ON);
}
public static void on(Context context,boolean on) {
if (on) Receiver.engine(context).isRegistered(); //
}
**********in reciver file***********
public void isRegistered ) {
Editor edit = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).edit();
edit.putString(Settings.PREF_STATUS+"","0");
edit.commit();
}
Instead of using edit.commit();, you should use edit.apply();. Apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.
commit()
Commit your preferences changes back from this Editor to the
SharedPreferences object it is editing. This atomically performs the
requested modifications, replacing whatever is currently in the
SharedPreferences.
Note that when two editors are modifying preferences at the same time,
the last one to call commit wins.
If you don't care about the return value and you're using this from
your application's main thread, consider using apply() instead.
apply()
Unlike commit(), which writes its preferences out to persistent
storage synchronously, apply() commits its changes to the in-memory
SharedPreferences immediately but starts an asynchronous commit to
disk and you won't be notified of any failures. If another editor on
this SharedPreferences does a regular commit() while a apply() is
still outstanding, the commit() will block until all async commits are
completed as well as the commit itself.
As SharedPreferences instances are singletons within a process, it's
safe to replace any instance of commit() with apply() if you were
already ignoring the return value.
You don't need to worry about Android component lifecycles and their
interaction with apply() writing to disk. The framework makes sure
in-flight disk writes from apply() complete before switching states.
Well, even if my answer came 3 years after the question, I hope it will help. The problem don't seem to came from commit or apply but from the code structure.
Let's explain: on a smartphone, you run an APP but you don't quit the APP as we do on computers.
This mean when you come back to the menu of the smartphone, the APP is still "running". When you "click" again on the APP icon, you don't re-run the APP but just awake it.
In juned code, we can see he calls getDefaultSharedPreferences inside his Create function.
So he calls getDefaultSharedPreferences when he runs first time the APP. But when he sets the APP on background and then awakes the APP, the call is not done.
I've had the same problem:
I check if I have SharedPreference for my APP. If not, I prompt a form to ask value to the user.
If yes, I check the date of the preferences. If too old, I prompt the form.
After the form, I save the preferences with the current date.
What I noticed is that the test about the existence of the SharedPreference (which was set at the same location than the one of juned) was done only at first run of the APP but not when I awake the APP. This mean that I was unable to check the time limite of my SharedPreferences!
How to solve that?
Just add:
#Override
public void onResume(){
super.onResume();
// And put the SharedPreferences test here
}
This code will be called at first run of the APP but also each time the user awake it.
hope it will help you..
SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEditr = mypref.edit();
prefsEditr.putString("Userid", UserId);
prefsEditr.commit();
String task1 = mypref.getString("Userid", "");
Try this code:
SharedPreferences edit = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = edit.edit();
editor.putString(Settings.PREF_USERNAME + "", txtuser);
editor.putString(Settings.PREF_PASSWORD + "", entered_name);
editor.commit();
Try like this,
public SharedPreferences prefs;
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Settings.PREF_USERNAME+"", txtuser);
editor.putString(Settings.PREF_PASSWORD+"", entered_name);
editor.apply()
Try like this,
public SharedPreferences prefs;
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Settings.PREF_USERNAME+"", txtuser);
editor.putString(Settings.PREF_PASSWORD+"", entered_name);
editor.commit();
Related
In my Android application for my school project I want to make it such that:
Every day, when you first open the application, it will start an activity. However, if you open the application again even after closing it from the multitasking view, it will not start the activity again.
I want it to be much like Elevate (https://www.elevateapp.com/) where on first startup it will say "Your training session for the day is ready" but never display this again if you open the app at another time in the day.
This is a screenshot of the activity:
I have tried using AlarmManager in this link Alarm Manager Example and searching for answers but it did not work for me and I couldn't find any.
Is there a way to make it possible? Thanks in advance.
We can use SharedPreferences to store the system date when the app is launched and verify if it is the same date or a different one every time the app s run.
If the date is different, store the new date into the SharedPreferences handle that you used.
To understand how to use SharedPreference to store data you can look at my answer here for an example.
First declare this two method on global level
public static void commitPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String readPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
now maintain your logic..
if (!readPref("CHECK_IF_RUN_TODAY", getApplicationContext()).equals(new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()))){
//YOUR LOGIC
commitPref("CHECK_IF_RUN_TODAY", new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()), getApplicationContext());
}
but dont forget to upadte your prefrence after your logic
Hope this helps..
I want to know how to check whether a checkbox is checked or not when an application is not running. Please help me. I'm making a call blocker, and I'm stuck.
When the application is not running, how can it check whether the checkbox is checked or not.
Android provides SharedPreferences class which is an utility that helps you to save user settings within your app internal memory and can be accessed by providing your application context.
Let's say that the user has checked the checkbox control, you could save that choice using SharedPreferences instance saving it onto disk.
For example:
myCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
SharedPreferences prefs = yourActivityContext.getSharedPrefences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor = prefs.edit(); //Create this instance in order to save data
editor.putBoolean("checked", isChecked); //Store the checkbox value
editor.commit(); //Call this to save the preferences to disk
}
}
);
Then in your BroadcastReceiver:
#Override
public void onReceive(Context context, Intent data) {
SharedPreferences prefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
boolean checkboxValue = prefs.getBoolean("checked", false);
//The second argument provide a default value if you haven't saved that setting before.
}
you can store checkbox value in database or web api and check through Android Services class.
Every time you start an application, a completely new instance of the program is created. And once the application terminates, the instance that was running no longer exists for you to check its state.
What you will have to do is...
Store the settings in a file or database when the program closes (or when the user hits "save" depending on how you design it)
When the application opens, have it read the settings and populate the screen (e.g., checkboxes) with its contents
If you didn't write the program that owns the checkbox (which wasn't clear in your original post), then the program must already do this; otherwise, it would have no way to re-populate the screen when it starts up. In this case, all you have to do is find out what the file or database table stores the info you need and figure out how to extract the data you need from that location.
Use SharedPreferences. In the onCheckChangedListener, just store a shared preferences with the boolean value associated with the checkbox. The broadcast receiver should have the same context, so you should be able to access the shared preference from there.
Im trying to use androids sharedpreferences, I´ve logged everything and the code below really commits the string set. The problem is when I force close the app and start again, the settings.getStringSet returns an empty set. No errormessages anywhere.
I´ve tried PreferenceManager.getDefaultSharedPreferences but that does not work for me either.
Thanks for you time.
public static final String PREFS_NAME = "MyPrefsFile";
private static final String FOLLOWED_ROUTES = "followedRoutes";
and later on when saved is called:
public void onFollowClicked(View view){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> follows = settings.getStringSet(FOLLOWED_ROUTES, new HashSet<String>());
follows.add(routeId);
editor.putStringSet(FOLLOWED_ROUTES, follows);
editor.commit();
}
You can also work around the bug mentioned by g00dy this way:
Get the set from sharedPreferences and save it in a variable.
Then just delete the set in sharedpreferences before adding it again when saving.
SharedPreferences.Editor editor= sharedPref.edit();
editor.remove("mSet");
editor.apply();
editor.putStringSet("mSet", mSet);
editor.apply();
Make sure to use apply() or commit() twice.
Alternatively, if you are working in Kotlin simply :
PreferenceManager.getDefaultSharedPreferences(applicationContext)
.edit {
this.remove("mSet")
this.apply()
this.putStringSet("mSet", mSet)
}
Take a look here.
Also for refference:
SharedPreferences
SharedPreferences.Editor
EDIT:
There's actually a bug with this one, see here. An extract from there:
This problem is still present on the 17 API level.
It is caused because the getStringSet() method of the
SharedPreferences class doesn't return a copy of the Set object: it
returns the entire object and, when you add new elements to it, the
commitToMemory method of the SharedPrefencesImpl.EditorImpl class see
that the existing value is equal to the previous one stored.
The ways to workaround this issue is to make a copy of the Set
returned by SharedPreferences.getStringSet or force the write to
memory using other preference that always change (for example, a
property that stores the size of the set each time)
EDIT2:
There might be a solution here, take a look.
I'm developing an app that has to share strings between activities. I'm trying to get the seperate activities to call a public class with set and get methods. The calling the methods part works and I manage to get a response although the set value has to be rememberd by the set and get class. Here's a link to my set and get class, it's pretty basic: http://pastebin.com/0WabNKz3
Now my question is this: How do I make the set and get class to remember my values between sessions? Feel free ask questions if there's anything you didn't understand.
Thanks!
You need to use SharedPreferences. That's the way to save data even after the app is closed and you can access it from anywhere:
public void savePrefrences(String key, String value)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
prefs.edit().putString(key, value).commit();
}
public String getPrefrences(String key)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
return prefs.getString(key, "");
}
Save the prefrence when and whereever you want and get it whenever and from wherver you want.
The value will not delete when you close the app.
I ended up creating invisible EditTextPreference that now hold the data that I want to keep because they can be shared easily.
When you say saving between sessions, do you mean between the app being paused, or closed completely?
A good resource for lifecycle and storing data across sessions is:
//developer.android.com/training/basics/activity-lifecycle/index.html
I'm obviously doing something wrong. On my splash screen, when it decides which activity to go to, I have the following code:
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean disclamerChecked = getPrefs.getBoolean("disclamer", false);
boolean medicalScreeningChecked = getPrefs.getBoolean("screening", false);
So, I'm trying to read 2 Boolean that should be false on app installation and
when the setup is done it should be permanently true.
Now, in my Activities (Disclamer only at the moment) I have the following thing:
private void setDisclamerPropertie() {
// TODO Auto-generated method stub
startupPrefs= getSharedPreferences("startupPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = startupPrefs.edit();
editor.putBoolean("disclamer", true);
editor.commit();
return;
}
This function is called in On Create function, and when "accept" button is clicked it should save the Shared Preference (Or at least that is what I need to happen).
Button works, it goes to next activity and that one goes to next again, but when I reload the App, it seems that Boolean are not saved and app asks again for the confirmations.
So, where am I wrong, in writing preferences, or something is missing in reading correct preferences?
You are reading from the default shared preferences, but writing to a named one ("startupPrefs"), so there are 2 separate instances of shared preferences
You're using different preferences.
startupPrefs= getSharedPreferences("startupPrefs", MODE_WORLD_WRITEABLE);
This should also be:
startupPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());