Xamarin Android - getting preferences from preferenceFragment - android

I have an app which uses preferenceScreen (checkboxes) for the user to turn on and off certain options. The preferences fragment which inflates the xml file looks like this:
public class BrandsFragment : PreferenceFragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
AddPreferencesFromResource (Resource.Menu.brandPrefs);
var prefs = PreferenceManager.GetDefaultSharedPreferences(this.Activity);
}
}
This works fine and i can successfully change the preferences.
However, what i need to do is get the preferences from the OnCreate method in my Main activity (not fragment).
This is what i have tried:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
wantGeneral = prefs.GetBoolean ("checkbox_preference_general", true);
Console.WriteLine ("Pref is " + wantGeneral);
SetContentView(Resource.Layout.NavigationDrawer);
.......
}
But the 'wantGeneral' preference always comes back true, regardless of the checkbox being checked. It's clear that from my Activity, it's not successfully grabbing the preferences.
What do i need to do in order to get the preferences from the Activity?

It appears that it was me not thinking it through properly. I needed to move the code into OnResume() or somewhere else that gets called after i make change to the preferences in my settings page. That way it pulls in the latest settings.

Related

Android Preference Summary in Preference Menu Not Persisting

I'm a bit unclear on how Preference.setSummary() is supposed to work. Is this method supposed to update a menu item's summary in a Preference fragment in a non-volatile way? In other words, is the displayed summary supposed to persist after closing and re-opening the preference menu fragment?
I thought it is supposed to work like this, yet any time I press the back button and then re-open the preference menu the summaries are blank again.
public class FragmentSettingsMenu extends com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from the XML resource
addPreferencesFromResource(R.xml.preferences);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key);
String color = woodPref.getSharedPreferences().getString(key, "Maple");
MainActivity.getGLSurfaceView().setTexture(color);
woodPref.setSummary(color); // Set summary to be the user-description for the selected value
}
}
};
}
}
Is this method supposed to update a menu item's summary in a Preference fragment in a non-volatile way?
No.
In other words, is the displayed summary supposed to persist after closing and re-opening the preference menu fragment?
No.

Can't resolve findPreference() from MainActivity?

I'm getting a compiler error cannot resolve method findPreference when I try to intialize an OnSharedPreferencesChanged listener in my MainActivity. According to the answer here:
findPreference() should be called from a class implementing PreferenceActivity interface
but I don't understand what the code to do this would be. How can I get rid of the compiler error and successfully set listeners for preference changes?
MainActivity.java
public class MainActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Test preference menu
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key); //COMPILER ERROR HERE
MainActivity.getGLSurfaceView().setTexture("");
// Set summary to be the user-description for the selected value
woodPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
findPreference is a method which is part of both PreferenceFragment and PreferenceActivity - these are the Fragments/Activities that actually show your Preference screen (the activity is deprecated and you should be using the PreferenceFragment).
You're trying to use it in your MainActivity. This doesn't work because the Preference objects don't actually exist on this screen (they exist in another activity that usually have a PreferenceFragment as part of it). If you need to get access to a preference value of a preference in an activity that is not your preference screen, use SharedPreferences, something like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getBoolean(R.bool.saved_high_score_default);
boolean wood = sharedPref.getBoolean(pref_wood, defaultValue);
You can check out the documentation for further examples.
If your MainActivity is supposed to be a screen that shows settings, then you should probably rename it and include a preference fragment inside of it.
I believe you're also going to run into trouble with setSummary because the Preference is not part of this activity, it's part of the activity where you actually modify the preferences. setSummary is used to update the actual UI of the Preference so that if you, for example, select one of three values when using a list preference, it shows the value you just selected on the screen.

Retrieving the preferences from the xml file in Android

I am new to Android and I am trying to handle the settings according to the instructions in
http://developer.android.com/guide/topics/ui/settings.html
I used the fragment based solution as the one directly in the activity was deprecated:
public class SettingFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingFragment())
.commit();
}
}
The settings are correctly displayed in the app, yet when I try to retrieve their values with:
sharedPref= PreferenceManager.getDefaultSharedPreferences(Dashboard.dashboard);
startDayTime=sharedPref.getString(SettingsActivity.day_switch_start, "");
startNightTime=sharedPref.getString(SettingsActivity.night_switch_start, "");
it complaints that values day_switch_start and night_switch_start might not be resolved. In fact, when I explode the values recognized by SettingActivity, I get a long list of capitalized strings part of the standard settings, but not my own strings.
Those were in fact just entered in the xml file and linked from the SettingFragment, so I doubt context Dashboard.dashboard I passed has any reference to it. Yet there are no instructions on how to pass the settings references to a specific context and moreover they say that the settings should be available from anywhere. I am stuck, any solution?
Thanks,
Please check the reference you linked again, especially the Reading Preferences section. When you set the preference key to, e.g., day_switch_start then you must use the same String when reading the preference, e.g.,
startDayTime=sharedPref.getString("day_switch_start", "");
You can also store the preference key to a constant like in the linked example:
public class SettingsActivity extends PreferenceActivity {
public static final String KEY_PREF_DAY_SWITCH_START = "day_switch_start";
// ...
and then access it when reading the preference:
startDayTime=sharedPref.getString(SettingsActivity.KEY_PREF_DAY_SWITCH_START, "");
Edit: I'm not sure what Dashboard.dashboard should represent but this should work:
sharedPref= PreferenceManager.getDefaultSharedPreferences(this);

Preference deactivating on its own in a PreferenceActivity

I have a PreferenceActivty in my Android app, which due to compatibility reasons I use via the getPreferenceScreen() method and some Preference objects which I create in code, mostly CheckBoxPreference and SwitchPreference.
Up to the previous version of my app there were 8 preferences in total and everything worked fine, but now I added 2 more preferences and I'm experiencing a REALLY weird issue.
The second preference on the screen is a SwitchPreference. When I open the activity, it is checked. If I scroll down the screen without actually changing anything, suddenly its value is automatically set to OFF. I tried adding an OnChangeListener to the Preference and implementing OnSharedPreferenceChangeListener, but the results are the same: once that particular Preference disappears from the screen, it is turned OFF. If it's set to OFF, it keeps its value and the change listener is not called.
Does anyone have any idea as to why could this be happening? I'm completely lost...
Thanks in advance!
The code for my preferences is basically this, repeated 5 times for 5 different settings, on the onCreate method:
controlWifiPreference = new CheckBoxPreference(this);
controlWifiPreference.setKey(Constants.PREF_1_KEY);
getPreferenceScreen().addPreference(controlWifiPreference);
wifiPreference = new SwitchPreference(this);
wifiPreference.setKey(Constants.PREF_2_KEY);
getPreferenceScreen().addPreference(wifiPreference);
Since the preferences are inside a TabActivity, on the onResume method I call setChecked() for every preference to set its value again, though I'm not sure that it's completely neccessary.
And, finally, I have an onSharedPreferenceChanged method that activates/deactivates preferences when others are clicked, because I couldn't get the setDependency method to work. It's something like this (again, repeated five times):
if (key.equals(controlWifiPreference.getKey())) {
wifiPreference.setEnabled(controlWifiPreference.isChecked());
}
Turns out it was an Android bug in the SwitchPreference class. Someone (who I'm VERY thankful to ;)) reported it to b.android.com and even posted a workaround. It's all here: https://code.google.com/p/android/issues/detail?id=26194
How you implemented preferences inside TabActivity?I checked your code in my own IDE inside a PreferenceActivity and its working like a charm.If you need to have some pseudo prefences inside your activity, you should not use prefernces and instead, you will need to use normal forms items and save their values to the preferences manually.here is the code i tested and its working ok:
public class PreferencesFromCode extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private SwitchPreference switchPref;
private CheckBoxPreference checkboxPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPreferenceScreen(createPreferenceHierarchy());
}
private PreferenceScreen createPreferenceHierarchy() {
// Root
#SuppressWarnings("deprecation")
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(
this);
// Inline preferences
PreferenceCategory inlinePrefCat = new PreferenceCategory(this);
inlinePrefCat.setTitle(R.string.inline_preferences);
root.addPreference(inlinePrefCat);
// Checkbox preference
checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("checkbox_preference");
checkboxPref.setTitle(R.string.title_checkbox_preference);
checkboxPref.setSummary(R.string.summary_checkbox_preference);
inlinePrefCat.addPreference(checkboxPref);
// Switch preference
switchPref = new SwitchPreference(this);
switchPref.setKey("switch_preference");
switchPref.setTitle(R.string.title_switch_preference);
switchPref.setSummary(R.string.summary_switch_preference);
inlinePrefCat.addPreference(switchPref);
/*
* The Preferences screenPref serves as a screen break (similar to page
* break in word processing). Like for other preference types, we assign
* a key here so that it is able to save and restore its instance state.
*/
// Screen preference
PreferenceScreen screenPref = getPreferenceManager()
.createPreferenceScreen(this);
screenPref.setKey("screen_preference");
screenPref.setTitle(R.string.title_screen_preference);
screenPref.setSummary(R.string.summary_screen_preference);
return root;
}
#Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
/*
* getPreferenceScreen().getSharedPreferences()
* .registerOnSharedPreferenceChangeListener(this);
*/
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Log.i("ghjg", "changed key is : " + key);
if (key.equals(checkboxPref.getKey())) {
switchPref.setEnabled(checkboxPref.isChecked());
}
}
}
However you may override onContentChanged() and see what happens.

How can i stop to be refreshed my values in android activity

I am working in android. I am designing a file upload functionality.
This is my layout:
If I fill my entries like as title,price,category and then I press browse button for browse option then I go to BrowseActivity using startActivity(). But when I come back to this activity then all entries which were filled by me disappear. please suggest me what should I do for this so my entered entries save. If I do browse first then fill entries then it works properly.
What should I do for the case in which user first fill entries and then click on the browse button?
Use the SharedPreferences options to save all the Strings in onPause(). You can get them back in onResume() and fill out your text boxes. This is also nice since you can save the values that were entered and restore them each time the user leaves the app for any other reason.
EDIT:
Quick example:
Save your strings like so:
#Override
public void onPause(){
super.onPause();
// Save the user preferences during runtime for later use.
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("title", "Value of title");
editor.commit();
}
Then you get get the value back like this.
#Override
public void onResume(){
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
String title = settings.getString("title");
}
Here is what you need to do.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("title", title.getText.toString());
//Do the same for the other 2 boxes.
super.onSaveInstanceState(savedInstanceState);
}
and in onRestoreInstanceState() pull the items out.
Like..
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
String Title = savedInstanceState.getString("title");
//Do the same for other String items you put into the bundle using the savedInstanceState() above. And then use EditText.setText(title); to set the text
}
The bundle is used exactly for this purpose. You Can get more info here
Check out android's shared preferences, they should give you an easy way to store data.
Android Shared Preferences
http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/reference/android/content/SharedPreferences.html
Another way is to create an object which holds the data you need, and don't new it in the onResume method...

Categories

Resources