Using Android preferences and dont show a variable to user - android

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

Related

Making PreferenceScreen not write to default SharedPreferences

I have a PreferenceScreen:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:id="#+id/checkBoxHighlightWeekends"
android:key="checkBoxHighlightWeekends"
android:summary="Weekends are different"
android:title="Highlight weekends" />
<MultiSelectListPreference
android:id="#+id/multiSelectListSelectWeekends"
android:key="multiSelectListSelectWeekends"
android:dialogTitle="Select weekends"
android:entries="#array/weekends"
android:entryValues="#array/weekends_values"
android:summary="Saturday, Sunday"
android:title="Select weekends"/>
</PreferenceScreen>
I'm trying to use only the "view" part of this and not make it write to it's default SharedPreferences. When user changes the preference, I manually check the changed data and send it to a MVVM repo, when then writes to my own custom SharedPreference. I plan to use LiveData to update the settings screen when it's opened. All this hassle because I'm trying to learn the MVVM architecture and Android in general.
Inside MainPreferenceFragment:
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_main);
CheckBoxPreference checkBoxHighlightWeekends = getPreferenceManager().findPreference("checkBoxHighlightWeekends");
MultiSelectListPreference multiSelectListPreference = getPreferenceManager().findPreference("multiSelectListSelectWeekends");
checkBoxHighlightWeekends.setOnPreferenceChangeListener(changeListener);
multiSelectListPreference.setOnPreferenceChangeListener(changeListener);
}
Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
// Call method in ViewModel which will save settings state to SharedPrefs
Logger.alert("Something changed! " + preference.getKey());
return true;
}
};
Any change to settings triggers the function, however the checkbox stops working - It doesn't change to the "tick" state anymore.
How can I strip out all the default click/change functionality from the PreferenceScreen and make it into a dumb view?

How do you create Preference Activity and Preference Fragment on Android?

As I was following an old tutorial (Créez des applications pour Android -> openclassroom) I got stuck on this deprecated method addPreferencesFromResource(int id) from the PreferenceActivity class.
So my question is :
What is the new way of creating Preferences in Android ?
I found this post (What to use instead of “addPreferencesFromResource” in a PreferenceActivity?) that help me understand that you have to go through a PreferenceFragment in order to do it.
In the following explanation I use your.package. just to show that you have to put the package name. Everybody has its own package so please replace it with your package.
lets begin :
1. Preference Fragment
Create your PreferenceFragment class
MyPreferenceFragment
public class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.fragment_preference);
}
}
Then the associated xml resource
fragment_preference.xml (in the folder res/xml of your project)
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="FOO">
<CheckBoxPreference
android:key="checkBoxPref"
android:title="check it out"
android:summary="click this little box"/>
</PreferenceCategory>
</PreferenceScreen>
That's all for the Fragment part.
2. Preference Activity
Create the PreferenceActivity class
MyPreferenceActivity
public class MyPreferenceActivity extends PreferenceActivity
{
#Override
public void onBuildHeaders(List<Header> target)
{
loadHeadersFromResource(R.xml.headers_preference, target);
}
#Override
protected boolean isValidFragment(String fragmentName)
{
return MyPreferenceFragment.class.getName().equals(fragmentName);
}
}
Do not forget to override isValidFragment(String fragmentName) method as you will get punched in the face by your application ! ;) More seriously I have no idea why you need to do this but it is needed. If someone has an explanation about this I'd gladly read it :)
EDIT :
Thanks to kirtan403 I now know why it is needed : it has to be set because of an (android framework fragment injection).
As you can see in the onBuildHeaders(List<Header> target) we load another xml file that contain the headers of the preference. In short, headers are the left part of the preference and the fragment are the right part (for tablet). For a phone you will first have the headers and when you click on an item the corresponding fragment will be put on top of the headers list.
Read this article (Multi-pane development in Android with Fragments - Tutorial) the images explain themselves.
Then the associated xml resource
headers_preference.xml (in the folder res/xml of your project)
<?xml version="1.0" encoding="utf-8"?>
<preference-headers
xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="your.package.MyPreferenceFragment"
android:title="Goto: Preference fragment"
android:summary="An example of some preferences." />
</preference-headers>
As you may have noticed in the header section you have :
android:fragment="your.package.MyPreferenceFragment"
This will act as a Link to the fragment you want to show. On Tablet it will load on the right part and on the phone it will load on top of the current view.
3. Android Manifest
Now what you should do is to add your Activity to the AndroidManifest.xml file.
Inside the application section add these lines :
<activity
android:name="your.package.MyPreferenceActivity"
android:label="Preferences">
</activity>
You will probably tell me :
"Oh darling you forgot to put android:launchMode="singleTask" in your actvity"
But DO NOT PUT THIS as you will never load your fragment on phone. This error was solved by a great man ! This is the link to his blog (Android header preferences on small screen/phone).
4. Start the Preferences from Menu
Finally you need to add the ability to show this Preference !! To do so you will need 3 things :
The Menu
menu.xml (in the folder res/menu of your project)
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/preferences"
android:title="Preferences" />
</menu>
Loading this Menu in your Main activity (not the PreferenceActivity) under the method onCreateOptionsMenu(Menu menu)
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
Starting the MyPreferenceActivity Activity when you click on that button.
For that you will need to override the onOptionsItemSelected(MenuItem item) method in your Main activity.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.preferences:
{
Intent intent = new Intent();
intent.setClassName(this, "your.package.MyPreferenceActivity");
startActivity(intent);
return true;
}
}
return super.onOptionsItemSelected(item);
}
Et voila les amis !
I haven't tested this code. I took it and modified it from my own code so I may have not well copy pasted things. If you encounter errors tell me, I'll try to figure out the problem and fix this.
I hope this post will help some people out there :D
Cheers !
I liked the solution from this post: http://alvinalexander.com/android/android-tutorial-preferencescreen-preferenceactivity-preferencefragment
.. because it seems the most compact for someone that just needs something very basic up and running quickly. It has only one .java file and two small xml files.
Activity Config REMINDERS
After adding the 3 files to your project, Don't forget to
A) Add the Prefs Activity to Manifest file
B) Add some way to launch the Prefs Activity .. e.g., a Button or Menu item
Add the following files to your project. Use the order they are listed in to avoid compile errors.
Add /res/values/array.xml
<resources>
<string-array name="listArray">
<item>Ace</item>
<item>Club</item>
</string-array>
<string-array name="listValues">
<item>Ace</item>
<item>Club</item>
</string-array>
</resources>
Add /res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:title="Your Name"
android:key="username"
android:summary="Please provide your username"></EditTextPreference>
<CheckBoxPreference android:title="Application Updates"
android:defaultValue="false"
android:summary="This option if selected will allow the application to check for latest versions."
android:key="applicationUpdates" />
<ListPreference android:title="Download Details"
android:summary="Select the kind of data that you would like to download"
android:key="downloadType"
android:defaultValue="Ace"
android:entries="#array/listArray"
android:entryValues="#array/listValues" />
</PreferenceScreen>
Add the Activity code
public class AppPreferenceActivity extends PreferenceActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
checkValues();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
private void checkValues()
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String strUserName = sharedPrefs.getString("username", "NA");
boolean bAppUpdates = sharedPrefs.getBoolean("applicationUpdates",false);
String downloadType = sharedPrefs.getString("downloadType","1");
String msg = "Cur Values: ";
msg += "\n userName = " + strUserName;
msg += "\n bAppUpdates = " + bAppUpdates;
msg += "\n downloadType = " + downloadType;
Toaster.shortDebug(msg);
}
}

Android Prefererences

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

Add link to Preferences?

I have preferences in an Android Live wallpaper app as below. (These are checkboxes). I want to add a link to a Facebook page to this list. Looking at Android PreferenceCategory on the net, I don't see anything like "LinkPreference" or "ButtonPreference", but then again, a link or button isn't really a preference, so maybe I'm trying to fit a square peg in a round hole. Is this possible and if so, how?
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
android:title="#string/livewallpaper_settings">
<PreferenceCategory android:title="#string/livewallpaper_settings" >
<CheckBoxPreference
android:defaultValue="true"
android:key="showred"
android:summary="Display red."
android:title="Display red" />
<CheckBoxPreference
android:defaultValue="true"
android:key="showgreen"
android:summary="Display green."
android:title="Display green" />
</PreferenceCategory>
</PreferenceScreen>
This question has been asked before:
Android Add Link to a preference activity - how?
but not answered.
[Edit]
So now have the code below. It does go to Facebook, but only after first clicking on one of the checkbox preferences.
In livewallpaper_settings.xml:
<PreferenceCategory android:title="#string/livewallpaper_settings" >
<Preference
android:key="facebook"
android:summary="#string/facebook"
android:title="#string/facebook" />
</PreferenceCategory>
LiveWallpaperSettings.java:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Log.d("LiveWallpaperSettings.onSharedPreferenceChanged()", "key: " + key);
final Preference mypref = (Preference) findPreference("facebook");
mypref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
Log.d("LiveWallpaperSettings", "mypref: " + mypref.getKey());
if (mypref.getKey().equals("facebook")) {
Log.d("LiveWallpaperSettings", "LINK TO FACEBOOK");
openWebURL("http://www.facebook.com");
return false;
}
return false;
} });
return;
}
public void openWebURL( String inURL ) {
Log.d("openWebURL", inURL);
Intent browse = new Intent( Intent.ACTION_VIEW , Uri.parse( inURL ) );
startActivity( browse );
}
How about an EditTextPreference? You can use the same attributes as an EditText in your EditTextPreference so you can restrict the input to a single line and display the correct IME for email input etc.

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

Categories

Resources