I've a checkbox and a ListPreference, I'd like disable/enable ListPreference by checkbox. I read a lot and I found is possible only using java (and not by xml). Is it correct? Now, after read the value of "checkboxPref" (boolean true/false) I don't how do.
SharedPreferences prefs3 = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String listpref) {
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
} };
prefs3.registerOnSharedPreferenceChangeListener(listener);
preferences.xml:
<CheckBoxPreference
android:title="Notifify"
android:defaultValue="true"
android:key="checkboxPref" />
<ListPreference
android:entries="#array/numberOptions"
android:entryValues="#array/numberValues"
android:key="number"
android:title="Number" />
Add
android:dependency="checkboxPref"
To the ListPreference XML
Result:
<ListPreference
android:entries="#array/numberOptions"
android:entryValues="#array/numberValues"
android:key="number"
android:title="Number"
android:dependency="checkboxPref"
/>
Related
I looked around but couldn't find a single tutorial that tells me how to use the switchpreference in my preference activity and in my main activity. I want to know how to implement it in my application using sharedpreference. Sample code would be appreciated. Thanks in advance
preference.xml:
<SwitchPreference
android:key="test"
android:title="Test" />
PreferenceActivity:
public class TestPrefActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.sample);
}
}
Register the shared preference object for the changes
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
sharedPrefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean test = sharedPreferences.getBoolean("test", false);
Log.e(TAG, "Value:" + test);
}
});
I'm having a comparable issue with another establishment of mine. I fixed it by using <SwitchPreference android:key="test" android:title="Test" />
In this preferenceScreen the user unlinks the device from his account. At the moment I just have it as Unlink device, once the user clicks it, the unlinking happens.
But I would like to add a piece text like this:
Joe Foo's Device (joefoo#gmail.com) - Unlink Device
Hoe would I do this? I also need to add the user name dynamically from settingsActivity.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference android:title="#string/pref_title_advanced_unlink" >
<TextView somehow must be in here
android:id="#id/user_name_and_email" />
<intent android:action="android.intent.action.VIEW"
android:targetPackage="com.example.tvrplayer"
android:targetClass="com.example.tvrplayer.UnlinkActivity"
android.setflags="FLAG_ACTIVITY_CLEAR_TOP"/>
</Preference>
</PreferenceScreen>
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:key="pref_title_advanced"
android:title="Advanced" >
<CheckBoxPreference
android:defaultValue="false"
android:key="pref_title_advanced_link"
android:title="Link Device" />
</PreferenceCategory>
</PreferenceScreen>
PrefsActivity.java
private SharedPreferences mPreferences;
private SharedPreferences.OnSharedPreferenceChangeListener mPrefListener;
private CheckBoxPreference mCheckBoxPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mCheckBoxPref = (CheckBoxPreference) getPreferenceScreen().findPreference(
"pref_title_advanced_link");
/*
* set initial summary as you desire. For example, userIdCurrent can be:
* "No Devices linked."
*/
mCheckBoxPref.setSummary(userIdCurrent);
mPrefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if (key.equals("pref_title_advanced_link")) {
/*
* set post-click summary as you desire. For example,
* userIdPost can be:
* "Joe Foo's Device (joefoo#gmail.com)".
*/
mCheckBoxPref.setSummary(userIdPost);
}
}
};
mPreferences.registerOnSharedPreferenceChangeListener(mPrefListener);
}
Preferences have a subtitle called summary. Give your preference a key, then you can use findPreference(CharSequence key) in your PreferenceFragment to get a reference to your preference object, sort of like calling findViewById to get references to Views. Then call setSummary(int) or setSummary(CharSequence) on the preference object.
Alternatively, you could do something entirely more complex by providing a custom layout for your preference objects and/or subclass Preference and implement some custom data binding. But I think the above should do what you want.
I have placed this into my PreferencesActivity
PreferencesActivity:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference preferences = findPreference("key");
preferences.setIntent(new Intent(getApplicationContext(), RegisterActivity.class));
}
preferences.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Preferences">
<Preference android:key="Pssword" android:title="Set SMS Notification Password"></Preference>
</PreferenceCategory>
</PreferenceScreen>
The moment i try to enter the preferences screen it crashes.
Your preference is called Pssword, not key.
You have a NullPointException because your key preference doesn't exist.
Replace your line Preference preferences = findPreference("key"); with Preference preferences = findPreference("Pssword");
This should resolve your issue.
I am struggling to restore the default values I specified in the preferences.xml, Here is my code:
Preference reset = findPreference(res.getString(R.string.DEFAULT_PREFS));
reset.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Preferences.this);
sp.edit().clear().commit();
PreferenceManager.setDefaultValues(Preferences.this, R.layout.preferences, true);
return true;
}
});
This code is my understanding of the android's developers reference for the function setDefaultValues(context, resId, readAgain):
Parameters
context The context of the shared preferences.
resId The resource ID of the preference hierarchy XML file.
readAgain Whether to re-read the default values.
Note: this will NOT reset preferences back to their default values.
For that functionality, use getDefaultSharedPreferences(Context)
and clear it followed by a call to this method with
this parameter set to true.
Well, it does not work, the preferences values are the same after this code is executed.
Then I looked into the SharedPreferences variable sp, and it points to a system generated file in the path:
/data/data/<packagename>/shared_prefs/<packagename>_preferences.xml
which I can only assume is the same xml I provided when I created the activity.
addPreferencesFromResource(R.layout.preferences);
Also inspecting the sp variable, the hash table has all the preferences, but there is no field for default value.
EDIT:
Before I am asked to, here is an excerpt from the preferences.xml file
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:defaultValue="5000"
android:key="#string/MAX_MESSAGES"
android:numeric="integer"
android:summary="#string/MAX_MESSAGES_desc"
android:title="#string/MAX_MESSAGES_title" />
<EditTextPreference
android:defaultValue="10"
android:key="#string/VIEW_EDGE_ROWS"
android:numeric="integer"
android:summary="#string/VIEW_EDGE_ROWS_desc"
android:title="#string/VIEW_EDGE_ROWS_title" />
<ListPreference
android:defaultValue="0"
android:entries="#array/level_list"
android:entryValues="#array/level_values"
android:key="#string/INITIAL_ORG"
android:summary="#string/INITIAL_ORG_desc"
android:title="#string/INITIAL_ORG_title" />
<ListPreference
android:defaultValue="2"
android:entries="#array/view_list"
android:entryValues="#array/view_values"
android:key="#string/INITIAL_VIEW"
android:summary="#string/INITIAL_VIEW_desc"
android:title="#string/INITIAL_VIEW_title" />
<CheckBoxPreference
android:defaultValue="true"
android:key="#string/AUTOSCROLL"
android:summary="#string/AUTOSCROLL_desc"
android:title="#string/AUTOSCROLL_title" />
<CheckBoxPreference
android:defaultValue="true"
android:key="#string/SEND_THEN_EXIT"
android:summary="#string/SEND_THEN_EXIT_desc"
android:title="#string/SEND_THEN_EXIT_title" />
<Preference
android:key="#string/DEFAULT_PREFS"
android:summary="#string/DEFAULT_PREFS_desc"
android:title="#string/DEFAULT_PREFS_title" />
</PreferenceScreen>
This is my solution so far. After debugging into the Android source code I find out that setDefaultValues() is not reliable and does not work as intended (at least according to my expectations).
I restore the default values manually now. I have a map where I can fetch from the default values.
Here is an interesting note: Inspecting the Preference class shows it has a field called mDefaultValue which contains the default value for the preference. But this field can only be set by setDefaultValue() method, and there is no method to get it. It would have save me the need for a Map
This is the code I use now, tested and working:
Preference reset = findPreference(getResources().getString(R.string.DEFAULT_PREFS));
reset.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Preferences.this);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
// PreferenceManager.setDefaultValues(Preferences.this, R.layout.preferences, false);
for(int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
restoreDefault(editor, getPreferenceScreen().getPreference(i));
}
editor.commit();
return true;
}
}
private void restoreDefault(Editor editor, Preference p) {
if(p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for(int i = 0; i < pCat.getPreferenceCount(); i++) {
restoreDefault(editor, pCat.getPreference(i));
}
}
if(p instanceof ListPreference) {
editor.putString(p.getKey(), resMap.get(p.getKey())._default);
}
if(p instanceof EditTextPreference) {
editor.putString(p.getKey(), resMap.get(p.getKey())._default);
}
if(p instanceof CheckBoxPreference) {
editor.putBoolean(p.getKey(), resMap.get(p.getKey())._default.equals("true"));
}
}
Another note: editor.commit() updates the preferences file, but does not update the preferences screen. You have to update each preference by using the listener (OnSharedPreferenceChangeListener()).
Given this code, how do I get the values from the checkbox- and textpreference and store them in the domain object?
public class MonitorPreferences extends PreferenceActivity {
private PersistenceManager pm;
private Monitor monitor;
private boolean mActive;
private String mName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pm = new PersistenceManager(getApplicationContext());
addPreferencesFromResource(R.xml.monitors_pref);
fetchDomainObject();
}
private void fetchDomainObject() {
monitor = pm.fetchMonitor(getIntent().getLongExtra(SuperListActivity.EXTRA_KEY_MONITOR_ID, -1));
}
private void persistDomainObject(Monitor monitor) {
pm.persist(monitor);
}
}
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="General">
<CheckBoxPreference
android:key="active_chkbox"
android:title="Active"
android:defaultValue="true"
android:persistent="false"/>
<EditTextPreference
android:key="name_txt"
android:dependency="active_chkbox"
android:title="Name"
android:summary="Enter a name"
android:dialogTitle="Enter a name"
android:dialogMessage="Enter a name"
android:defaultValue="John Doe"
android:persistent="false"/>
</PreferenceCategory>
</PreferenceScreen>
Original question: Creating a normal Activity with the look and feel of a PreferenceActivity
My goal is to edit the variables of a domain object from an Activity with the look and feel of stock android preferences. What's the easiest way of accomplishing this?
Would it be possible to create a a PreferenceActivity and somehow modify it to display/edit the values of a domain object instead of the values from SharedPreferences?
Of course. Just add the code to store the values into the database and don't forget to mension android:persistent=false attribute in your preferences xml.
final CheckBoxPreference soundcb = (CheckBoxPreference) findPreference("active_chkbox");
Further you can do many things with soundcb object: read the value, set onClickListeners and so on.