checkbox value in other activity - android

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.

Related

SharedPreferences not writing / reading

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?

Set<String> in android sharedpreferences does not save on force close

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.

Error loading SharedPreferences on startup

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

SharedPreferences value is not updated

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

I want to clear the value of the shared preference

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

Categories

Resources