How to add ListPreference in this Activity? - android

I am a newbie at android development and I am trying to implement a Settings Activity so that it can take user preferences. This is my Settings Activity which already includes code to handle Edit Preference changes.The module is implemented for Android 3.0 and above hence Settings Fragment is used.
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_general);
}
#Override
public void onResume(){
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause(){
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key){
if(key.equals("location")){
Preference loc_preference=findPreference("location");
loc_preference.setSummary(sharedPreferences.getString(key,""));
}
}
}
}
This is the pref_gen.xml file
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="#string/pref_loc_key"
android:dialogMessage="#string/location_dialog_message"
android:dialogTitle="#string/location_dialog"
android:title="#string/pref_loc_label"
android:defaultValue="#string/pref_default_loc"
android:selectAllOnFocus="true"
android:singleLine="true" />
<ListPreference
android:key="#string/pref_unit_key"
android:dialogTitle="#string/unit_dialog_message"
android:title="#string/pref_unit_label"
android:defaultValue="#string/pref_default_unit"
android:entries="#array/pref_unit_options"
android:entryValues="#array/pref_unit_values" />
This is the arrays.xml file
<string-array name="pref_unit_options">
<item>Metric</item>
<item>Imperial</item>
</string-array>
<string-array name="pref_unit_values">
<item>1</item>
<item>0</item>
</string-array>
Can anyone help me to add the List Preference module in the Settings Fragment method along with a listener? I have gone through other posts but somehow I cant modify it accordingly.

You can use getPreference to reference ListPreference in java and then register listener on it.
ListPreference unit_preference = mContext.getPreference(<Key>);
unit_preference .setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChanged(Preference preference, Object newValue) {
//Do something with newValue here
}
});
Note: mContext is a class variable of type Context. You must set it before calling beginTransaction:
mContext = this;

Related

show sharedpreference on preference activity

I'm struggling to figure out how to show the preference in the preference activity. I'm simply trying to show the high score and i keep getting the same 345 value show up. I have confirmed in debugging that the new high score is saved . Here is all my code.
preferences.xml
<Preference
android:title="High Score"
android:selectable="false"
android:defaultValue="0"
android:key="#string/pref_highest_score"/>
HighScoreActivity.java
public class HighScoreActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new HighScoreFragment()).commit();
}
public static class HighScoreFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onResume(){
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
}
strings.xml
<!-- High Score settings -->
<string name="pref_highest_score">345</string>
<string name="title_activity_high_score">High Score</string>
MainActivity.java
preferences = PreferenceManager.getDefaultSharedPreferences(context);
Assets.highScore = preferences.getInt(context.getString(R.string.pref_highest_score), 1);
editor = preferences.edit();
editor.putInt(context.getString(R.string.pref_highest_score), currentPoints );
editor.apply();
It's because your preference screen does not actually gets the value of pref_highest_score. You should find the preference and call Preference.setSummary(). Like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Gets the preference defined in XML
Preference p = findPreference("#string/pref_highest_score");
// Sets the summary of the preference to the high score
p.setSummary(
String.valueOf(preferences.getInt(context.getString(R.string.pref_highest_score), 1))
);
}
where preferences is PreferenceManager.getDefaultSharedPreferences(context).
And in your XML, specify an id of the preference:
<Preference
android:key="#string/pref_highest_score"
android:title="High Score"
android:selectable="false"
android:defaultValue="0"/>

PreferenceFragment doesn't invoke on onSharedPreferenceChanged

onSharedPreferenceChanged isn't called when preferences is changed, I use following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings2);
getFragmentManager().beginTransaction().replace(android.R.id.content, new Frag()).commit();
}
public static class Frag extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
System.out.println(key);
}
}
pref.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference android:title="show floating touch" android:defaultValue="false"></SwitchPreference>
</PreferenceScreen>
it doesn't invoke onSharedPreferenceChanged when i change SwitchPreference, why?
the code SwitchPreference doesn't set android:key:
<SwitchPreference android:title="show floating touch" android:defaultValue="false"></SwitchPreference>
when change it to:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference android:key="show_float_toucher" android:title="show floating toucher" android:defaultValue="false"/>
</PreferenceScreen>
it work
I found useful the following link for the same problem :
How to listen for preference changes within a PreferenceFragment?
code sample:
public class PrefActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PrefFragment()).commit();
}
public static class PrefFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set xml
addPreferencesFromResource(R.xml.pref);
// set texts correctly
onSharedPreferenceChanged(null, "");
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("show_float_toucher"))
{
//TODO
}
}
}
}
Tip: check you minSdkVersion !
best regards!

Preference onClick Not Detected

i have setup an onpreference click listener for a preference but it fails to fire even though the preference is found by the find preference command.
Activity
public class PreferenceActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content
setContentView(R.layout.activity_preference);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
Context context;
private final String DOB = "date";
private SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
context = getActivity().getApplicationContext();
Preference dob = findPreference(DOB);
Log.i("test", dob.getKey() + "");
dob.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Log.i("test", "2");
return false;
}
});
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
}
}
The preference xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="My Account">
<EditTextPreference
android:key="profile_name"
android:summary="Taylor Swift"
android:title="Username" />
<Preference
android:key="date"
android:summary="N.A."
android:title="#string/date" />
</PreferenceCategory>
</PreferenceScreen>
The log output for "test" correctly displays the key of the preference but the log within the onclick never fires.
I've created simple project with your code and everything seems to be working fine.
Log.i("test", "2");
is being called when I click "Date" field.

SharedPreference Change Listener and custom preference

I have those preference:
<xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:key="pk1"
android:title="#string/pt1"
android:summary="#string/pt1s"
android:defaultValue="false" />
<CheckBoxPreference
android:key="pk2"
android:title="#string/pt2"
android:defaultValue="false" />
<ListPreference
android:key="pk3"
android:title="#string/pt3"
android:dialogTitle="#string/pt3"
android:entries="#array/fontsi"
android:entryValues="#array/fontsiv"
android:defaultValue="0" />
<Preference
android:key="pkb"
android:title="#string/ptb" />
</PreferenceScreen>
And the settings activity:
public class SettingsActivity extends PreferenceActivity {
SharedPreferences.OnSharedPreferenceChangeListener lst;
SharedPreferences prf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
prf = getPreferenceScreen().getSharedPreferences();
lst = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Log.i("SettingsActivity","!any preference changen!");
if (key.equals("pk1")) { Log.i("SettingsActivity","!pref PK1 called!"); } }
else if (key.equals("pkb")) { Log.i("SettingsActivity","!pref PKB called!"); }
prf.registerOnSharedPreferenceChangeListener(lst);
}
#Override
protected void onResume() {
super.onResume();
prf.registerOnSharedPreferenceChangeListener(lst); }
#Override
protected void onPause() {
super.onPause();
prf.unregisterOnSharedPreferenceChangeListener(lst); }
...
}
The listener works with all the preferences but e custom preference (the last one, pkb as key)!
That i want to use as a back button.
Anybody knows why ?
Obviously your preference doesn't change any preferences.
Since it doesn't do anything, OnSharedPreferenceChangeListener ignores it.
A possible solution would be to set a clickListener to it like this:
findPreference("pkb").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Log.i("SettingsActivity", "!pref PKB called!");
return false;
}
});

PreferenceActivity do something when preference are changed

I have preference xml and following code:
public class MainActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getApplicationContext(), "DO SOMETHING", Toast.LENGTH_LONG).show();
}
}
I want to get notified over toast message, when one or more preferences are changed. I think upper code should work, but for some reason it doesn't.
I have for example CheckBoxPreference in my xml file. And when I check or uncheck CheckBox I want to be notified.
You have to set the listener like this for example:
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(this);
or, if You donĀ“t use the default shared preferences, You have to get Your prefs and then register them:
SharedPreferences preferences = getSharedPreferences("your_shared_prefs", Context.MODE_PRIVATE);
preferences.registerOnSharedPreferenceChangeListener(this);
You should register to listen to the shared preference changes:
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

Categories

Resources