Android Prefererences - android

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

Related

android.preference.Preference.setOnPreferenceClickListener() does not work

I want to set an intent from my SettingsFragment (extends PreferenceFragment) to another activity within my app. I tried using the following code at first: (I'm using android.preference.Preference)
preferences.xml (the root preferences)
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
...
<PreferenceCategory android:title="About">
<Preference
android:key="about_here"
android:title="About us"
android:enabled="true" />
</PreferenceCategory>
</PreferenceScreen>
Then, in my SettingsFragment.java:
public class SettingsFragment extends PreferenceFragment {
public static final String goToAbout = "about_here";
private ViewGroup parent;
private View currView;
#Override
public void onCreate(#Nullable Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference preferencex = findPreference(goToAbout);
preferencex.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(getActivity(), AboutActivity.class);
i.putExtra("Class", "Settings");
preference.setIntent(i);
Log.e("Preference", "Clicked");
getActivity().startActivity(i);
return true;
}
});
}
...
}
However, the onPreferenceClick code is not invoked at all (I know from the Log.e() that it does not happen). I know that many have asked this question before, but even implementing their solutions does not help. Is there anything I'm missing?
Also, I don't mind implementing an Intent from within preferences.xml, but I tried that and it returns an error.

Android preferences how to work with switch statement

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;
}

Update EditTextPreference title when other preference is pulsed in Android

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;
}
});

Preference Screen option is not showing

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
}
}**

Using Android preferences and dont show a variable to user

I have a sharedPreferences implementation where I store user preferences. When the user clicks "preferences" in menu, I open the standar editor to allow the user to change preferences. This is the code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.MENU_PREFERENCES:
Intent intent = new Intent(context, PreferencesActivity.class);
startActivity(intent);
return true;
case xx:
....
}
Toast.makeText(this, "ERROR: Bad menu item", Toast.LENGTH_SHORT).show();
return true;
}
In PreferencesActivity.java I have:
public class PreferencesActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
My question is if can I have a variable in the preferences for internal use, I mean, that will not be showed to user when startActivity(intent)? how?
I suppose I must change something in preferences.xml but dont know exactly what....
thanks
EDIT: as requested, I paste xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory>
<ListPreference android:title="Pomodoro duration" android:key="pomodoro_duration" android:summary="Duration of each pomodoro" android:entryValues="#array/array_duration_values" android:defaultValue="25" android:entries="#array/array_duration"/><ListPreference android:key="short_break_duration" android:title="Short break duration" android:summary="Duration of break after each pomodoro" android:entryValues="#array/array_duration_values" android:entries="#array/array_duration" android:defaultValue="5"/>
<ListPreference android:title="Long break interval" android:summary="Interval of the longer break" android:key="intervalos" android:entryValues="#array/interval_array_values" android:defaultValue="4" android:entries="#array/interval_array"/>
<ListPreference android:defaultValue="20" android:title="Long break duration" android:summary="Duration of break after each pomodoro" android:key="long_break_duration" android:entries="#array/array_duration" android:entryValues="#array/array_duration_values"/><RingtonePreference android:title="Notification sound" android:ringtoneType="notification" android:summary="Tone that will sound after pomodoro ends" android:key="notification_tone" android:showDefault="true" android:showSilent="true"/>
<ListPreference android:summary="Period used to calculate productivity" android:title="Calculus period" android:key="calculus_period" android:entryValues="#array/array_calculo_valores" android:entries="#array/array_calculo"/>
</PreferenceCategory>
</PreferenceScreen>
When I inveke the standar UI to allow user to set this variables, I would like to hide one of them programmaticaly. Is possible?
If it is not in preferences.xml, it won't be displayed, so just don't add it there. You can use the SharedPreferences class to get/set preferences without displaying a UI. Something like:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean flag = prefs.getBoolean("flag", false);

Categories

Resources