I've an Android application with a setting menu. I've some EditTextPreferences that when is changed a button in the UI changes too. Moreover, I would like to implemente a Preference that reset the values of all EditTextPreferences. Now I have:
preference.xml
<PreferenceScreen
android:key="custom_balizamiento"
android:persistent="false"
android:title="#string/balizamiento" >
<EditTextPreference
android:defaultValue="#string/custom_event_1"
android:key="custom_event_balizamiento_1"
android:title="#string/custom_event_1" />
<EditTextPreference
android:defaultValue="#string/custom_event_2"
android:key="custom_event_balizamiento_2"
android:title="#string/custom_event_2" />
</PreferenceScreen>
<Preference
android:key="button_reset"
android:summary="#string/pref_reset_summary"
android:title="#string/pref_reset" />
SettingsFragment.java
Preference buttonreset = (Preference) findPreference("button_reset");
buttonreset.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
pref.edit().clear();
pref.edit().commit();
pref.edit().apply();
updatePreference();
pref.edit().commit();
pref.edit().apply();
return true;
}
});
public void updatePreference() {
Map<String, ?> keys = pref.getAll();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getKey().contains("custom_event")) {
Preference auxpref = findPreference(entry.getKey());
String newValue = pref
.getString(entry.getKey(), entry.getKey());
auxpref.setTitle(newValue);
}
}
pref.edit().commit();
}
When I pulse the reset prefence, nothing change. However, when I close the settings fragment and open it again the preference and the button in the UI changes to the default value. How can I update the button and the preference when I pulse the reset preference?
Finally I found the solution. I've changed the Listener code:
Preference buttonreset = (Preference) findPreference("button_reset");
buttonreset.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
pref.edit().clear().commit();
pref.edit().apply();
updatePreference();
pref.edit().commit();
pref.edit().apply();
PreferenceManager.setDefaultValues(getActivity(), R.layout.preferences, true);
pref.edit().apply();
return true;
}
});
Related
I have some preferences in my preference screen:
<PreferenceCategory
android:key="category"
android:summary="Category"
android:title="Category">
<Preference
android:key="pref1"
android:summary="desc"
android:title="Pref 1" />
<Preference
android:key="pref2"
android:summary="desc"
android:title="Pref 2" />
</PreferenceCategory>
Finding them in PreferenceActivity:
Preference pref1, pref2;
#Override
protected void onCreate(final Bundle savedInstanceState) {
pref1 = findPreference("pref1");
pref2 = findPreference("pref2");
}
And set some OnPreferenceClickListener to them. How do I correctly define which preference was clicked? I'd like to do it in case-switch style, but I cannot figure out which types should I use:
Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
switch (???){ //I guess, here goes the "preference"?
case ???: //getting error with pref1 or pref2
}
return false;
}
}
If I put preference from onPreferenceClick in switch(), I will get errors with case.
You can get the corresponding preference like
#Override
public boolean onPreferenceClick (Preference preference)
{
String key = preference.getKey();
// do what ever you want with this key
}
ref: Preference Activity on Preference Click Listener
hope this helps :)
You can use the field key of Preference
public boolean onPreferenceClick(Preference preference) {
if (preference.getKey().equals("pref1")) {
... do something ...
} else if (preference.getKey().equals("pref2")) {
... do something ...
}
return true;
}
I use this library to create my PreferenceActivity. It works quite fine so far but I can not set any listeners on my Preference.
That how my Activity looks like:
public class PrefActivity extends UnifiedSherlockPreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
setHeaderRes(R.xml.preference_headers);
// Set desired preference file and mode (optional)
setSharedPreferencesMode(Context.MODE_PRIVATE);
super.onCreate(savedInstanceState);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Preference p = (Preference)findPreference("deleteSavedSearches");
p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
//code for what you want it to do
return true;
}
});
}
}
This is my PreferenceScreen:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference
android:key="deleteSavedSearches"
android:summary="Gespeicherte Suchen löschen"
android:title="Gespeicherte Suchen löschen" />
</PreferenceScreen>
And those are my headers:
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:unified="http://schemas.android.com/apk/res-auto" >
<!--
/*
** Header definitions are identical to android:* except for preferenceRes which should be a reference to a preference xml file
** Unlike the native headers these are also used for building the single pane version.
*/
-->
<header
unified:fragment="com.example.skelett.PrefActivity$GeneralPreferenceFragment"
unified:preferenceRes="#xml/pref_country"
unified:title="Land" />
<header
unified:fragment="com.example.skelett.PrefActivity$GeneralPreferenceFragment"
unified:preferenceRes="#xml/pref_data"
unified:title="Daten" />
</preference-headers>
In this case, p is null. getPreferenceScreen() also always returns null. I have my keys set up in the preference xml. What am I missing?
Just move the findPreference method in onPostCreate and should work:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Preference p = (Preference) findPreference("deleteSavedSearches");
p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
// code for what you want it to do
return true;
}
});
}
I'm coming to think my problem is with my preferences not being done correctly is why i cannot access tem. Here is My preferences:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/pref_user_profile"
android:textSize="20px"
android:layout="#layout/pref_layout">
<SwitchPreference
android:title="#+string/pref_frequency"
android:summary="#+string/pref_frequency_summary"
android:key="frequency"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:title="#+string/pref_time"
android:summary="#+string/pref_time_summary"
android:key="time"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:title="#+string/pref_symptothermal"
android:summary="#+string/pref_symptothermal_summary"
android:key="symptothermal"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:title="#+string/pref_cervical_mucus"
android:summary="#+string/pref_cervical_mucus_summary"
android:key="cervical_mucus"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:title="#+string/pref_mucus_stamps"
android:summary="#+string/pref_mucus_stamps_summary"
android:key="mucus_stamps"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:title="#+string/pref_fertile_infertile"
android:summary="#+string/pref_fertile_infertile_summary"
android:key="fertile_infertil"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
</PreferenceCategory>
</PreferenceScreen>
Java:
package com.projectcaruso.naturalfamilyplaning;
import com.projectcaruso.naturalfamilyplanning.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class UserSettingActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Here is my call to the settings menu:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final int RESULT_SETTINGS = 1;
switch (item.getItemId()) {
case R.id.projectcaruso:
Util.goToGitHub(this);
return true;
case R.id.about:
new AlertDialog.Builder(this)
.setTitle(R.string.about)
.setMessage(Html.fromHtml(getString(R.string.about_msg)))
.show();
break;
case R.id.licenses:
new AlertDialog.Builder(this)
.setTitle(R.string.licenses)
.setMessage(Html.fromHtml(getString(R.string.license_detail)))
.show();
break;
case R.id.contact:
break;
case R.id.settings:
Intent j = new Intent(this, UserSettingActivity.class);
startActivityForResult(j, RESULT_SETTINGS);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.settings, menu);
return true;
}
}
So any help would be appreciated! I'm trying to access these preferences but cannot. It seems to be saving them just fine. I am able to test and run the code, change the pref's and it saves their state. However when i try to access them i cannot... Here's the code i used to try and access them:
EDIT:
I've changed it to call as the following and no matter the setting it is still the "Hello toast 2!"
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = this.getActivity().getSharedPreferences("UserSettingActivity",0);
// Inflate the layout for this fragment
Boolean symptothermal = preferences.getBoolean("symptothermal", true);
if (!symptothermal) {
Context context = getActivity().getApplicationContext();
Toast.makeText(context, "Hello toast 1!", Toast.LENGTH_LONG).show();
} else {
Context context = getActivity().getApplicationContext();
Toast.makeText(context, "Hello toast 2!", Toast.LENGTH_LONG).show();
}
if (!symptothermal) {
TextView temp = (TextView) getView().findViewById(R.id.temp);
temp.setVisibility(View.GONE);
}
}
The problem is how you are trying to access them.
You use this line:
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
When to access the preferences that are stored through a PreferenceActivity you should call the default preferences.
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
That is it.
Edit
If you are making a call to getDefaultSharedPreferences() from a Fragment, you simply need to change the value you pass as parameter. this in the above example is a context, to call this from the Fragment, do the following:
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
Probably you trying to read prefs from a different file.
Add getPreferenceManager().setSharedPreferencesName("pref"); to UserSettingActivity and see if it will help
My Preference Screen option is not showing, it shows-app. has stopped unexpectedly..
This is my Preference.java-
public class Prefs extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.id.settings);
}
}
This is the settings for Preference-
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:key="music"
android:title="#string/music_title"
android:summary="#string/music_summary"
android:defaultValue="true"/>
<CheckBoxPreference
android:defaultValue="true"
android:summary="#string/hints_summary"
android:title="#string/hints_title"
android:key="hints"/>
</PreferenceScreen>
This is the Item Select event-
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.settings)
{
startActivity(new Intent(this,Prefs.class));
return true;
}
return false;
}
And the activity is registered well in manifest file.
<activity
android:name=".Prefs"
android:label="#string/settings_title" >
</activity>
addPreferencesFromResource()
method should load XML file containing the preferences.
Therefore, in you code replace
addPreferencesFromResource(R.id.settings)
with
addPreferencesFromResource(R.xml.yourPreferenceSettingsFileHere)
That will solve your problem.
please replace addPreferencesFromResource(R.id.settings); with addPreferencesFromResource(R.layout.settings);
where settings is the preference xml.
and instead of using onOptionsItemSelected()
use
onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
final String key = preference.getKey();
if(key.equal("music"){
/ur implementaion
}
}**
I'm making a backup and restore options in my android app. Then you open the preference I want a button to backup and a button to restore.
I make the button in my xml/preference.xml file like this:
<PreferenceCategory android:title="Backup">
<Preference
android:key="backup"
android:title="Backup"
android:summary="Make a backup of shows"
/>
<Preference
android:key="restore"
android:title="Restore"
android:summary="Restore shows from backup"
/>
</PreferenceCategory>
I my preference class I implements OnSharedPreferenceChangeListener, and add getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); to onResume() and getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); to OnPause().
The i implements onSharedPreferenceChanged:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Let's do something when my counter preference value changes
if (key.equals("backup")) {
Toast.makeText(this, "Backup button pressed", Toast.LENGTH_SHORT).show();
} else if (key.equals("restore")) {
Toast.makeText(this, "Restore button pressed", Toast.LENGTH_SHORT).show();
}
}
But no toast is displayed then i press one of the buttons. I works fine on i.e. CheckBoxPreference, but i only need a button, not the checkbox. Some one who can help?
If it is just a simple button then there is no preference that can be changed, so your onSharedPreferenceChanged will not be called in this case.
Use an OnClick listener instead:
OnPreferenceClickListener btnListener = new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String key = preference.getKey();
if (key.equals("backup")) {
// show toast
return true; // we handled the click
}
return false; // we didn't handle the click
}
};
Preference prefBtn = findPreference("backup");
prefBtn.setOnPreferenceClickListener(btnListener);
put your code to
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference);
method. preference here is the preference that were clicked.