I want to use a preferences.xml file for storing/retrieving application wide preferences. Where do I store the xml file so that I can use:
getSharedPreferences("preferences", 0)
My preferences.xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory>
<Preference android:key="units_length" android:title="imperial" android:summary="Whatever"></Preference>
<Preference android:title="imperial" android:key="units_weight" android:summary="Whatever"></Preference>
</PreferenceCategory>
</PreferenceScreen>
And here is how the onCreate method looks like in my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
// Get preferences
preferences = getSharedPreferences("preferences", 0);
// Fetch the text view
TextView text = (TextView) findViewById(R.id.textView1);
// Set new text
text.setText(preferences.getString("units_length", "nothing"));
}
My application just says "nothing".
Thanks.
Put it in the res/xml directory.
Related
I´m having trouble with setting preferences in my app.
In the main layout I have the button to open the settings layout:
Button btnPreferences = (Button) findViewById(R.id.btnPreferences);
btnPreferences.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent("com.absolutkarlos.AppPreferenceActivity");
startActivity(i);
}
});
Then, it open the PreferenceActivity:
public class AppPreferenceActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//--load the preferences from an XML file---
addPreferencesFromResource(R.xml.user_references);
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="True of False"
android:key="checkboxPref" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<EditTextPreference
android:summary="Enter a string"
android:defaultValue="#string/food"
android:title="Edit Text"
android:key="editTextPref"
android:name="#string/name"/>
<RingtonePreference
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref"
android:name="Ringtone Preference" />
<PreferenceScreen
android:title="Second Preference Screen"
android:summary=
"Click here to go to the second Preference Screen"
android:key="secondPrefScreenPref" >
<EditTextPreference
android:summary="Enter a string"
android:title="Edit Text (second Screen)"
android:key="secondEditTextPref"
android:name="EditText" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Everything looks like its going to work ok, but when I test it, don´t save the string I want it to save.
I Mean, I click the setting button, open the setting layout, I write a text on the EditTextPreference call NAME, but it doesn´t save it, instead the LogCat: sendUserActionEvet() mView == null
So, what I´m doing wrong? Did I miss a step? or forgot to add something?
Basically, I just want to user write his name as part of the settings, this name will be shown at the main layout as a big title. The user can write a nickname if he want. It´s just a string that the app must remember always.
Thanks for your help...
As you might have read, the message:
LogCat: sendUserActionEvet() mView == null
can be ignored on S4 devices.
You need read the value of Preference, and change it, for his title, on your AppPreferenceActivity, set onResume method:
#Override
public void onResume(){
super.onResume();
EditTextPreference preference = (EditTextPreference) findPreference("secondEditTextPref");
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setTitle(newValue.toString());
return true;
}
});
String name = preference.getText();
if(name != null)
preference.setTitle(name);
}
Also, you must remove addPreferencesFromResource method, because is deprecated. You should use onBuildHeaders method. Here you can see an example of PreferenceActivity.
So I have EditText in my Preferences and i want to get the text it and use it as String.Then i want to use that string everytime when my button is clicked and it will set my another EditText text to the string from Preference. Codes :
<EditTextPreference android:title="Uredi Text"
android:key="ime"
android:summary="ime pjesme"
/>
Java code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String b1t = preferences.getString("ime", "DEFAULT");
et1 = (EditText) findViewById(R.id.editText1);
//Button Click
public void button(View view) {
et1.setText(b1t);
}
According to the developer docs, you can just use edittextpreference.getText().toString()
http://developer.android.com/reference/android/preference/EditTextPreference.html
I'm not sure where your error is so I'll just give you my code for doing this.
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext();
String string = sharedPreferences
.getString("key", "default");
And in my preferences
<EditTextPreference
android:defaultValue="default"
android:key="key"
android:summary="I'm a summary"
android:title="I'm a title" />
For the onCLick method to modify the edit text
EditText editText = (EditText)
findViewById(R.id.editText);
editText.setText(String.valueOf(string));
This code works. If your application still crashes then your issue is either with your onClick event or something else. I personally prefer onClickListeners for buttons.
Heres the code for an onClickListener.
Button button = (Button)
findViewById(R.id.button);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Do some awesome stuff
}
});
edit: John posted his answer before mine, and his answer reflects most use cases, such as in a standard Activity. My answer is directed solely at the use of a PreferenceActivity.
Here's how you can add Preferences with defaults based on another Preference within a PreferenceActivity. Sorry if there are any errors, I'm typing on my phone.
Your XML-defined Preferences will have their values saved to SharedPreferences automatically, but code-created Preferences will need to be saved/persisted manually.
PreferenceActivity's onConfigurationChange() usually saves the state of code-created preferences (nested PreferenceScreens are a bit strange.)
And, of course, you'll want to do null checks (omitted to save my thumbs.)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Preferences"
android:key="root">
<EditTextPreference android:title="Default Pref Text"
android:key="ime"
android:summary="ime pjesme"
/>
<Preference android:title="Click to add a preference."
android:key="add"
android:summary=""
/>
</PreferenceScreen>
MyActivity.class
public class MyActivity extends PreferenceActivity {
public void onCreate(Bundle inState) {
super.onCreate(inState);
setContentView(R.layout.activity_main);
getPreferenceScreen.findPreference(PREFERENCE_BUTTON).
setOnPreferenceClickListener(new OnNewPrefClickListener());
}
private class OnNewPrefClickListener implements OnPreferenceClickListener {
public boolean onPreferenceClick(Preference preference) {
PreferenceScreen rootScreen = getPreferenceScreen();
EditTextPreference defaultPref =
(EditTextPreference)rootScreen.findPreference("ime");
String defaultText = defaultPref.getText();
EditTextPreference newPref = new EditTextPreference(getApplicationContext());
newPref.setText(defaultText);
rootScreen.addPreference(newPref);
return true;
}
}
}
I have PreferenceActivity in my app and I want to specify custom layout for EditTextPreference.
I do it in an xml file with android:layout attribute. All is OK, the layout is getting changed but I can't change any value of its fields. The code is running without errors, in debug I can see that values are changed, but visually there are no changes.
I've tried to call view.invalidate() and onContentChanged() but nothing changed.
All of IDs are OK and no exceptions are being thrown. So I have no idea. I'll appreciate you help.
Here is code of my preferences_file_types.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:key="#string/preference_category_file_types"
android:title="#string/settings_supported_file_types" >
<EditTextPreference
android:key="#string/preference_file_type_image"
android:layout="#layout/file_types_list_item"
android:title="#string/settings_supported_file_types_hint" />
</PreferenceCategory>
</PreferenceScreen>
Here is code of my PreferenceActivity class:
public class FileTypesSettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_file_types);
LayoutInflater inflater = getLayoutInflater();
EditTextPreference imageTypePreference = (EditTextPreference) findPreference(getString(R.string.preference_file_type_image));
View specifiedView = inflater.inflate(imageTypePreference.getLayoutResource(), null);
changeViewAttributes(specifiedView);
}
private void changeViewAttributes(View view) {
ImageView fileTypeIcon = (ImageView) view.findViewById(R.id.file_types_list_item_iv_icon);
fileTypeIcon.setBackgroundResource(R.drawable.ic_file_image);
TextView fileTypePredefined = (TextView) view.findViewById(R.id.file_types_list_item_tv_predefined_extensions);
fileTypePredefined.setText("JPG BMP GIF PNG");
TextView fileTypeAdded = (TextView) view.findViewById(R.id.file_types_list_item_tv_added_extensions);
fileTypeAdded.setText("BLA BLA BLA");
}
}
I need to remove a PreferenceCategory programmatically. I could remove the individual preferences with the following code but I need to remove (disable) whole PreferenceCategory as well.
PreferenceScreen preferenceScreen = getPreferenceScreen();
EditTextPreference etp = (EditTextPreference) preferenceScreen.findPreference("pref22");
((PreferenceGroup) findPreference("prefcat")).removePreference(etp);
Edit: Here's the working code for a PreferenceCategory "prefcat" and a child preference "pref22":
PreferenceScreen preferenceScreen = getPreferenceScreen();
EditTextPreference etp = (EditTextPreference) preferenceScreen.findPreference("pref22");
PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("prefcat");
if (preferenceGroup != null) {
preferenceGroup.removePreference(etp);
preferenceScreen.removePreference(preferenceGroup);
}
you can hide a category by getting reference to PreferenceScreen:
I your xml :
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#string/preferenceScreen">
//set all you values
//Preference, PreferenceCategory and/or CheckBoxPreference
</PreferenceScreen>
in you string.xml :
don't forgot to set this new string
<string name="preferenceScreen" translatable="false">preferenceScreen</string>
in you code:
preferenceScreen = (PreferenceScreen) findPreference(getResources().getString(R.string.preferenceScreen));
and then remove the category from your PreferenceScreen :
myCategory = (PreferenceCategory) findPreference(getResources().getString(R.string.my_category));
myPreferenceScreen.removePreference(myCategory);
Don't load the PreferenceCategory in the first place.
If you are defining your preferences in Java, don't create the PreferenceCategory.
If you are defining your preferences in XML, use three XML files:
One for stuff before this magic category
One for the magic category
One for stuff after this magic category
In situations where you want the category, load all three XML files. In situations where you do not want the category, load only the first and third XML files.
Provide a key for your PreferenceScreen and your PreferenceCategory in XML:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="preferenceScreen" >
<PreferenceCategory
android:summary="#string/settings_billing_summary"
android:title="Title"
android:key="myPrefCat" >
<Preference
android:key="someKey"
android:summary="Sum"
android:title="Title" />
</PreferenceCategory>
</PreferenceScreen>
From your class, you can now refer to your preferenceScreen and preferenceCategory and use the removePreference() method to remove the preference from the screen:
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preferenceScreen");
PreferenceCategory myPrefCat = (PreferenceCategory) findPreference("myPrefCat");
preferenceScreen.removePreference(myPrefCat);
This answer is based on douarbou's answer which appears to be outdated, but is basically the same.
You can find the entire child-parent tree by traversing over all of the preferences and then check which is the parent of any preference you wish, even without using the id of the parent:
public static Map<Preference,PreferenceGroup> buildPreferenceParentTree(final PreferenceActivity activity)
{
final Map<Preference,PreferenceGroup> result=new HashMap<Preference,PreferenceGroup>();
final Stack<PreferenceGroup> curParents=new Stack<PreferenceGroup>();
curParents.add(activity.getPreferenceScreen());
while(!curParents.isEmpty())
{
final PreferenceGroup parent=curParents.pop();
final int childCount=parent.getPreferenceCount();
for(int i=0;i<childCount;++i)
{
final Preference child=parent.getPreference(i);
result.put(child,parent);
if(child instanceof PreferenceGroup)
curParents.push((PreferenceGroup)child);
}
}
return result;
}
sample usage:
final Map<Preference,PreferenceGroup> preferenceParentTree=buildPreferenceParentTree(SettingsActivity.this);
final PreferenceGroup preferenceGroup=preferenceParentTree.get(preferenceToRemove);
preferenceGroup.removePreference(preferenceToRemove);
EDIT: seems there is a new API for this :
https://developer.android.com/reference/androidx/preference/Preference#setVisible(boolean)
I'm not sure if currently it's available or not, though.
I've got a preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Category">
<CheckBoxPreference
android:key = "inputPreferences"
android:title = "Title"
android:summary = "Subtitle"/>
</PreferenceCategory>
</PreferenceScreen>
I want to read out the value of the CheckBoxPreference, and depending on it, there sould be shown (for example) a TextView. I tried following code, but it doesn't work:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onResume", Toast.LENGTH_LONG).show();
SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
if(myPreference.getBoolean("checkbox", false)) {
VarText.setVisibility(View.VISIBLE);
VarText.setText("foo");
}
}
Hope anyone can help, thanks :)
you need to be using the key attribute that you set in your xml file. Change the android:key to "checkbox" rather than "inputPreferences"