I want to create a settings class one. I've created one myself right now. For example, I created a key switch called camera. This clicklistener how do I do this?
SettingsActivity Class:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
}
Settings Activity XML:
<androidx.preference.PreferenceCategory
android:key="the_key_to_retrieve_the_preference_in_code">
<androidx.preference.SwitchPreference
android:key="camera"
android:summary="...."
android:title="Camera" />
<androidx.preference.SwitchPreference
android:key="reset"
android:summary="..."
android:title="Reset" />
<androidx.preference.Preference
android:key="key"
android:summary="subtitle"
android:title="title" />
<androidx.preference.Preference
android:key="key2"
android:summary="subtitle2"
android:title="title2" />
<androidx.preference.CheckBoxPreference
android:key="key_for_check_box"
android:summary="subtitle"
android:title="title" />
</androidx.preference.PreferenceCategory>
</PreferenceScreen>
Follow that steps
1. In oncreate you should make default setting and put the in shared prefs like this
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Key","Value");
editor.apply();
And here change the flag for if settings are default or not. So first time when user open app everything by default and you set default values when he changed something the flag of default is changing and next time he come back this step ignores
2. On each switcher you have to make check and get value from shared preferences like this.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Key", "Value");
if(!name.equalsIgnoreCase("") && !name.equalsIgnoreCase("default")
{
// Switcher change state
}
Optional: You could optimize it by adding one more flag to check were there any changes after last update in that case just go and update each switcher but this is the easiest way. Either you could check if user open app first time or not by adding on null check
Conclusion: Check if first time just put everything with default values from shared preferences -> than if change switcher state just change the same in shared pref -> when come back to setting activity extract all values from each switcher from shared preferences
Related
I've got a Preferenceactivity with a EditTextPreference.
What I'm looking for is the command to access the inserted text of the EditTextPreference from a fragment.
What I have so far:
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String name = preferences.getString("edit_text_preference_name", "Default");
I allways get "Default" instead of my actual inserted text from the EditTextPreference.
Thanks in Advance.
Edit:
from SettingsActivity.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class BarcodePreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_barcode);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("edit_text_preference_barcode"));
bindPreferenceSummaryToValue(findPreference("edit_text_preference_name"));
}
}
pref.xml
<EditTextPreference
android:capitalize="words"
android:defaultValue="#string/pref_default_display_name"
android:key="edit_text_preference_name"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="#string/pref_default_display_name" />
From the documentation of PreferenceFragment:
To retrieve an instance of SharedPreferences that the preference hierarchy in this fragment will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this fragment.
This means that the PreferenceFragment saves the values to the default shared preferences which leaves you two options:
Option 1 - Use the default SharedPreferences to retrieve the saved value
It's pretty simple, you need to call the PreferenceManager's getDefaultSharedPreferences(...) static method to access the default shared prefs. So instead of
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String name = preferences.getString("edit_text_preference_name", "Default");
do
// use getActivity() instead of getContext() if you're using the framework Fragment API and min SDK is lower than 23
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String name = preferences.getString("edit_text_preference_name", "Default");
Option 2 - Set your PreferenceFragment to use named shared prefs
You can set the name of the used shared prefs in your BarcodePreferenceFragment's onCreate(...) method by calling setSharedPreferencesName(...) on the belonging PreferenceManager:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("pref");
// the rest of your code
}
I have a Preference Screen in my android app which contains a call to the system settings via an inner Preference and some Switches options as below:
<PreferenceCategory
android:title="#string/preferences_activity_supervisor_settings_title">
<Preference
android:key="#+id/instrument_preference"
android:title="#string/instrument_settings"
android:summary="#string/instrument_settings">
</Preference>
<com.CustomSwitchPreference
android:key="#string/prefs_super_autosend_key"
android:title="#string/prefs_super_autosend_title"
android:summary="#string/prefs_super_autosend_summary"
android:defaultValue="false"/>
...
...
My class extends PreferenceFragment and I added the resources using addPreferencesFromResource(). It works without problems.
However, the method onPreferenceTreeClick(), when I click in the Fragment (keyID = instrument_preference) the preferences always brings me key as NULL. All other options in the preference fragment I can read the key.
The question is why and how I detect the user clicked in the first element of my preference list ?
First remove + from #+id, because every time it create a new key due to #+id, thats why you get null.
And to detect SharedPreference is changed use this simple code:
public class MyPreferences extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.fw_preferences); //deprecated
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// handle the preference change here
}
}
Try removing #+id before the preference key name
It should be like
<Preference
android:key="instrument_preference"
android:title="#string/instrument_settings"
android:summary="#string/instrument_settings">
</Preference>
So I am trying to implement a preferences menu in my app. I used the standard generated template in android studio. THe issue is that now I can't figure out how save the values the user specifies. I thought about using a click listener to determine when a user clicked a checkbox and then getting the actual value of the checkbox and saving that to sharedpreferences, but I can't figure out how to do it.
Does anyone have any suggestions on how use onClick in a preference activity?
OK, we seem to be on the right track about the system storing the values automatically, but whenever I try to reference them from my main class, it always returns null. Here is my code:
boolean trueorfalse = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean("my_key", false)
;
So I assume you've already defined your Preferences in res --> xml and it looks something like this:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="my_key"
android:summary="#string/desc_string"
android:title="#string/title_string" />
</PreferenceScreen>
As soon as the user checks or unchecks the CheckBox the systen will automatically create an entry in the default Preference-file which you can access like this:
PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("my_key", false);
But back to your initial question: If you want to assign an onClick-Listener to your preference you have to do something like this:
Preference myPreference = (Preference) findPreference("my_key");
myPreference .setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// do something
}
});
Note: In this example it isn't a CheckBoxPreference, it's just a simple Preference
I tried the same in my SettingsMenu by implementing OnSharedPreferenceChangeListener
public class SettingsMenu extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Context context = getApplicationContext();
SharedPreferences menu_settings = PreferenceManager.getDefaultSharedPreferences(context);
menu_settings.registerOnSharedPreferenceChangeListener(this);
...
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// check the checkboxes
}
}
Hope it helps :)
in the onCreate method of my PreferenceActivity i set some Properties like this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("pref_mykey", true);
editor.commit();
It seems to work but the View is not updating so when i open the properties the onCreate runs and changes the values. I will then see the "old" values on the Screen until i close and reopen the prefs screen, then i do see the new properties.
I already tried this after the commit:
((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();
But without any effect. I still see the "old" Prefs until i close and reopen the PreferenceActivity .
What am i doing wrong? How can i refresh the PreferenceActivity after setting values in the onCreate method?
Thanks a lot for your help.
This was buggin me all day but finally found a solution.
((ListPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setValue(code);
Your example is with a boolean so it'll have to change based on what kind of preference it is.
IE:
((CheckBoxPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setChecked(true);
If you use a PreferenceFragment than you need to inject the PreferenceScreen in the activity.
public class SettingsActivity extends Activity implements ScanFragment.OnFragmentInteractionListener {
private PreferenceScreen prefScreen;
public void setPreferenceScreen(PreferenceScreen prefScreen){
this.prefScreen = prefScreen;
}
#Override
public void onFragmentInteraction(String scanContent) {
// commiting to editor retrieved from preference manager would not refresh view
EditTextPreference pref = (EditTextPreference)this.prefScreen.findPreference(getString(R.string.preference_url_key));
pref.setText(scanContent);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
((SettingsActivity)this.getActivity()).setPreferenceScreen(this.getPreferenceScreen());
}
}
}
I use a Preference in a PreferenceActivity to load default values: when this specific Preference is clicked, something like this happens:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
But afterwards, the Preferences whose corresponding SharedPreference was reset still show the old value - it seems to be cached in the Preference. Only when I leave the PreferenceActivity and reopen it, the Preferences show the new values.
How can I update the PreferenceActivity programmatically?
I had a similar problem. This probably isn't the most correct fix but it worked for my purposes. Right after I did the commits, I called the Activity.recreate(); method.
The activity will restart (onDestroy()/onCreate()/etc) but for my purposes all I needed was a special handling on one preference. I listened for a certain preference with an OnPreferenceClickListener and made an alert dialog box with a kind of warning message and an option to change their mind. If they did want to change their mind, I did my commit of the new value to the preference activity and then called recreate() so that the checkbox preference would be updated.
However, I am also interested in a way to do this without recreating the activity...
Update preference value without reloading PreferenceActivity
from http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Here is how to update default shared preference value of target element (in this case EditTextPreference)
public class YourCustomPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
// some logic goes above, when you want to reset value and update EditTextPreference value
// For convenience, I am going to wrap two different task in different methods
private void resetPreferenceValue() {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefEditor = sharedPref.edit(); // Get preference in editor mode
prefEditor.putString("your_edit_text_pref_key", "DEFAULT-VALUE"); // set your default value here (could be empty as well)
prefEditor.commit(); // finally save changes
// Now we have updated shared preference value, but in activity it still hold the old value
this.resetElementValue();
}
private void resetElementValue() {
// First get reference to edit-text view elements
EditTextPreference myPrefText = (EditTextPreference) super.findPreference("your_edit_text_pref_key");
// Now, manually update it's value to default/empty
myPrefText.setText("DEFAULT-VALUE"); // Now, if you click on the item, you'll see the value you've just set here
}
}