get and set listPreference from another activity not working - android

I'm trying to get and set a listPreference value from different activities and it's not working.
When I read and write it from my main activity, it only keeps whatever I write, so I'm assuming that I'm not targeting the listPreference correctly when I'm out of the activity because it's working inside my preference activity no problem.
I've seen some references on the developer website to CharSequence with getValue and getEntryValues but I haven't had luck getting them to work correctly either.
Here is my code for clicking a button and setting the listpreference value then it launches an intent to switch activities:
Main Activity, attempting to set the value of the listpreference to the first index value;
SharedPreferences settings = getSharedPreferences("PreferenceXML",
MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("ListPreferenceInXML", "1");
editor.commit();
String levelCheck = settings.getString("ListPreferenceInXML","1");
In my next activity I call read the value on launch to see which listPreference is active and it is always the number I write from the mains activity listed above. The problem is when I goto the actual Preference activity and it doesn't match or update when I change it on the ListPreference and launch the same activity from there (it still reads the value I set from the Main activity button)
code as follows for activity trying to read ListPreference:
SharedPreferences settings = getSharedPreferences("PreferenceXML",
MODE_PRIVATE);
Toast.makeText(this, settings.getString("ListPreferenceInXML","1"), 1000).show();

So I finally figured it out, the problem was with the way I was calling the preferences. Instead of calling the preferences like this, in both cases;
SharedPreferences settings = getSharedPreferences("PreferenceXML",
MODE_PRIVATE);
Call them like this:
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
I'm not sure if there is a step missing out of the first way of calling the preferences but this 2nd way worked like a champ.

Related

Updating Preference UI instance from another activity?

How do i update a Prefence UI instance that i created in a Setting Activity from another activity (Main Activity)?
I tried using these lines in Main Activity to update the Preference within Settings Activity, but I get ClassCastException.
Preference IsFeature =(Preference)((PreferenceActivity)context).findPreference((getString(R.string.key_enable_feature)));
IsFeature.setEnabled(True);
Just wondering whether theres another way to do this?
Any help, feedback or answers would be great!
You can try this:
In xml of settings get the "key" attribute from element you want to change (in bottom example it's "example_switch"). Than put this code in onClick method of button or wherever else you want to. This below takes the preference of switch in general settings and sets its value to false.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("example_switch", false); // "example_switch" - "key" attribute of your element | false - value
editor.commit();

Getting the state of checkbox preference from an activity in android

i have kept background music for my android app by default.I have used preference for closing the music when the user wants.Now i want to check in an activity whether the checkbox is checked or not..How can i access the preference checkbox from any other activity..How can i implement it?
You can use this:
SharedPreferences preferences = getSharedPreferences("pref",
Context.MODE_PRIVATE);
boolean x = preferences.getBoolean("mycheckbox",false);
"mycheckbox" is the key that you have used when creating preference check box.
<CheckBoxPreference
android:key="mycheckbox"/>

SharedPreferences dependencies

I wanted to create ListPreference which, when changed will also reload values of others ListPreference objects. I tried to do that by calling:
if(key.equals("important_pref")) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("some_pref", "some_val");
editor.apply();
}
in onSharedPreferenceChanged function.
It does the work but I need to reload preferences screen to see the efect. Is there a way to avoid that and reload values instantly?
My guess is that I can't do this that way, because the first commit needs to be ended before changing something else.
This is a very common requirement that is unfulfilled I'm afraid. You either have to reload the screen by hacks like setPreferencesScreen(null); or (better) register a SharedPreferencesChanged listener and update the prefs manually. See : update preferences values after changing them programatically
In your case you should add if clauses in your existing SharedPreferencesChanged listener to "hear" the change in the "some_pref" preference and update the displayed value manually.

CheckBoxPreference Default Value

I have a CheckBoxPreference defined as follows:
<CheckBoxPreference
android:defaultValue="true"
android:key="prefVisible"
android:summary="#string/pref_visible_summary"
android:title="#string/pref_visible" >
</CheckBoxPreference>
My application uses this preference to control the visibility of a view. When I first start my application (on a new wiped emulator) the view is not shown. However, when the I go to the preferences screen (activity) the checkbox is shown as checked.
Does this mean that the defaultValue attribute is not actually setting the preference but rather it's just setting the value of the checkbox if there is no underlying data (as would be the case on a brand new install). And does this also mean that the preference is set only after the user enters/exits the preferences screen (activity) for the first time, otherwise it's undefined?
Note that in order to get my app to work the way I intended it to work I relied on the default value argument to the preferences getter method as follows:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isVisible = sharedPrefs.getBoolean("prefVisible", true); // default = true
This leaves me a bit confused as to why there are 2 ways to control the default value of a preference: defining it in the Xml or providing the default value in the getBoolean method.
No the preferences can be set if you call PreferenceManager.setDefaultValues. So if you call this when the first time the app is launched then your view will be shown.
You can read more at http://developer.android.com/guide/topics/ui/settings.html

Showing preference screen first time app is run and related questions

I have an app with 2 activities, the preference and the main activity, I need the preference screen to show first time the app is run so the user can do some configuration. I have checked through the answers on this topic and they don't seem very clear but I gather it has to do with checking that there are sharedpreference file is empty.
Can someone please give me a code to sort this out and on which activity would I put the code?
Also I am still in the developing stage so I already have my preferences setup how do I undo this?
Thanks in Advance
1) When your main activity starts check a boolean preference with the default set to false. If it is false, launch your preference activity, if it is true then you know you have saved it to be true!
SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
boolean haveWeShownPreferences = prefs.getBoolean("HaveShownPrefs", false);
if (!haveWeShownPreferences) {
// launch the preferences activity
} else {
// we have already shown the preferences activity before
}
2) In your preferences activity save the same boolean preference with a value of true in onCreate
SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("HaveShownPrefs", true);
ed.commit();
I assume that you're running an emulator, when you start the emulator you have the choice to "wipe saved data" when you start it so it will be like you started it as if you just started the application. Alternatively, you can go into settings -> Applications -> You app -> Wipe data.
In regards to your coding solution, I don't have anything handy at the moment, but what you should do is start your main activity, run a procedure/function to check if the sharedpreference file is empty, and if it is start the preference activity, otherwise run your main activity. Alternatively, instead of checking for the file to be empty, you could see if a value that you are looking for user input (for example UserID) is null or not. If that value isn't null that means that the application can continue.
I've sorted this out with this bit of code in my main activity
if (prefs.getString("edittextpref", null) == null)
{
startActivity(new Intent(this, Preferences.class));
return;
}
}
It just checks if one of your values is empty but you need to put this at the bottom of onCreate or else when you go back to the main page it will be blank.
I am doing something like this. And its works for me.
String path = "//data//data//"+this.getPackageName()+"//shared_prefs//feedbackpref.xml";
boolean exists = (new File(path)).exists();
if (exists) {
introWindowNavigate=false;
}

Categories

Resources