I am trying to fill a ListPreference with the contents of the res/anim folder but I am having a problem it keeps coming up blank, I have a static array of strings to fill it and that works but I need it to be dynamic, I can print the text out in the logcat, its just not populating the list can you help me?
PreferenceActivityMenu.java
CharSequence[] entries = null;
CharSequence[] entryValues = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
ListPreference prefListAnim = new ListPreference(this);
listAnim();
prefListAnim.setEntries(entries);
prefListAnim.setEntryValues(entryValues);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
return false;
}
public void listAnim() {
Field[] fields = R.anim.class.getFields();
entries = new String[fields.length];
entryValues = new String[fields.length];
for (int count = 0; count < fields.length; count++) {
Log.i("Raw Asset: ", fields[count].getName());
entries[count] = fields[count].getName();
entryValues[count] = Integer.toString(count);
}
}
and preference.xml
<PreferenceCategory android:title="Animation Transitions" >
<ListPreference
android:dialogTitle="#string/prefsList_dialogTitle"
android:key="prefList_animations"
android:summary="#string/prefsList_summary"
android:title="#string/prefsList_title" >
</ListPreference>
</PreferenceCategory>
Thanks for your help
You are setting the list data to a different preference than the one declared in xml. Currently you're setting the data against a newly created ListPreference:
ListPreference prefListAnim = new ListPreference(this);
However, you're displaying the (empty) one declared in xml. You should do either one or the other. For example, the easiest solution is probably to change above to inflate the preference from xml in stead:
ListPreference prefListAnim = (ListPreference) findPreference("prefList_animations");
Related
I have two Spinners. In onCreate i setup listeners for them. At some other places i populate them.
Now I am not sure what the best practice is for handling these spinners when screen orientation changes. Should i store all values and selected item in sharedPreferences somehow or in savedInstanceState?
If you can, please advise me in a prefered way and also include some sample code for handling spinners. The goal here is to keep the values and selected item thru the lifecycle.
I will include code at request or if needed.
Thanks
Try this, onSaveInstanceState for Screen Orientation for saving your selected value of spinner,According to my choice shared preference is not good choice for saving selected values of spinner.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("mySpinner", mySpinner.getSelectedItemPosition());
// do this for each or your Spinner
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize all your visual fields
if (savedInstanceState != null) {
mySpinner.setSelection(savedInstanceState.getInt("mySpinner", 0));
// do this for each of your text views
}
}
Add android:configChanges="orientation|screenSize" in your AndroidManifest file, it will keep spinner value selected on orientation change.
User Spinner Like this:
mSpinner = findViewById(R.id.spinner);
ArrayList<String> stringArrayList = new ArrayList<>();
for (int i = 0; i < 6; i++) {
stringArrayList.add("List Item " + i);
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stringArrayList);
spinner.setAdapter(arrayAdapter);
In my code, with the help of context menu I'm able to delete a particular item from Listview but as I'm using sharedpreferences to save arraylist called "places" then it restores the sharedpreference when the app is launched back again. Now how should I implement my sharedpreferences such that when a particular item is deleted from listview, the same item also gets deleted from arraylist "places" of shared preferences.
Below is my code snippet
static ArrayList<String> places = new ArrayList<String>();
static ArrayList<LatLng> locations = new ArrayList<>(); //to save lat and long
static ArrayAdapter arrayAdapter;
public ListView listView;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
sharedPreferences = this.getSharedPreferences("com.starprojects.memorableplaces", Context.MODE_PRIVATE);
registerForContextMenu(listView);
//tricker locations
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
//initially set
places.clear();
latitudes.clear();
longitudes.clear();
locations.clear();
//to restore
try {
places = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList<>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes", ObjectSerializer.serialize(new ArrayList<>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes", ObjectSerializer.serialize(new ArrayList<>())));
Log.i("palces",places.toString());
} catch (IOException e) {
e.printStackTrace();
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
// sharedPreferences = getSharedPreferences("places",0);
SharedPreferences.Editor editor = sharedPreferences.edit();
if((item.getTitle()).equals("Delete"))
{
places.remove(info.position);
editor.remove("places"); //problem is here, how to get particular index to be removed from arraylist places and save it.
editor.commit();
arrayAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
}
you can get index by
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
it means you must a list in you shared preference or you have a different key for your shared preference.
Case 1: if you have a list in your shared preference than update the shared preference with the remove of data of data from the listview.
Case 2: if you assigned different key_names for each of the list item then you can simply remove or clear that key_name when the data is removed from the shared preference.
If I'm getting the point of your question you are trying to keep the shared preferences copy up to date with the one you display and vice-versa.
To accomplish this I think that you just need to put the updated places array list into shared preferences, like this:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
SharedPreferences.Editor editor = sharedPreferences.edit();
if ((item.getTitle()).equals("Delete")) {
// Update local list
places.remove(info.position);
// Set list into shared preferences
// Or if you use a JSON string you could serialize and use putString()
editor.putStringSet("places", places);
// Use apply it's async
editor.apply();
arrayAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
Please use apply() in place of commit(). It's faster and asynchronous
I'm trying to programmatically create a ListPreference, which I can do but when I select it, it's list of entries is empty. I believe I am correctly setting the setEntries() and setEntryValues() with CharSequence arrays, but it's just empty when I select it.
Please find below the ActivitySetting class. Please note I'm using PreferenceFragments as to not use deprecated methods. But I only have one PreferenceFragment which is currently set as default
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
// Create the new ListPref
ListPreference customListPref = new ListPreference(getActivity());
// Get the Preference Category which we want to add the ListPreference to
PreferenceCategory targetCategory = (PreferenceCategory) findPreference("TARGET_CATEGORY");
CharSequence[] entries = new CharSequence[]{"One", "Two", "Three"};
CharSequence[] entryValues = new CharSequence[]{ "1", "2", "3" };
// IMPORTANT - This is where set entries...looks OK to me
customListPref.setEntries(entries);
customListPref.setEntryValues(entryValues);
customListPref.setTitle("Title");
customListPref.setSummary("This is the summary");
customListPref.setDialogMessage("Dialog Message");
customListPref.setPersistent(true);
// Add the ListPref to the Pref category
targetCategory.addPreference(customListPref);
}
}
}
Here is the Setting.xml it just has the single PreferenceCategory which the ListPreference is added to:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Some Options" android:key="TARGET_CATEGORY">
</PreferenceCategory>
</PreferenceScreen>
Here is what I get. The ListPreference has been successfully but when I select it.... No entries :( I'm expecting the options: "One", "Two", "Three"
Found it if you set the setDialogMessage() then this overwrites the contents so by removing this line, it works now.
You might want to replace setDialogMessage() by setDialogTitle() to get the title back.
I have a preference activity and have noticed that a list preference does not set default values when changed.
The Preference has these basic dynamics
If Checkbox = unticked --> list preference entry values = x
if Checkbox = ticked --> list preference entry values = z
When the app first runs default value is set but when I tick the checkbox no values apply after that.
CODE:
public class QuickPrefsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
View title =(View)getWindow().findViewById(android.R.id.title);
FrameLayout titlebar=(FrameLayout)title.getParent();
TextView txt = (TextView)titlebar.getChildAt(0);
txt.setGravity(Gravity.CENTER);
CheckBoxPreference chckbox = (CheckBoxPreference)
findPreference("french");
if (chckbox.isChecked()) {
ListPreference newsPref = (ListPreference)
findPreference("news_feed");
newsPref.setEntryValues(getResources().
getStringArray(R.array.newsfeedfr));
newsPref.setDefaultValue(1);
} else {
ListPreference news2Pref = (ListPreference)
findPreference("news_feed");
news2Pref.setEntryValues(getResources().
getStringArray(R.array.newsfeed));
news2Pref.setDefaultValue(1);
}
}
}
you need to add onPreferenceChangeListener like below...
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("french");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("true") {
// add your code here if checkbox is checked.
}
else {
// add your code here if checkbox is not checked.
}
return true;
}
});
Method setDefaultValue() takes an Object as argument, rather than index in values array. So, you should rewrite your code something like this:
String[] values = getResources().getStringArray(R.array.newsfeed)
news2Pref.setEntryValues(values);
news2Pref.setDefaultValue(values[0]);
Moreover, you should probably set entry titles too:
news2Pref.setEntries(your_titles_array_here);
I have a ListPreference and I want to show the current entry in the summary. According to the docs for ListPreference.getSummary(), I'm supposed to be able to do this by including %s in the summary string. Unfortunately, the activity just displays the %s in the summary.
The XML is pretty standard:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="displayMode"
android:summary="#string/display_mode_summary"
android:title="#string/display_mode"
android:defaultValue="BOTH"
android:entries="#array/displayModes"
android:entryValues="#array/displayModeValues"
/>
</PreferenceScreen>
The value of the string display_mode_summary is just %s. (The value "BOTH" is present in the displayModeValues array.) If I subclass ListPreference like this:
public final class DisplayModePreference extends ListPreference {
// ...
#Override
public CharSequence getSummary() {
return String.format(super.getSummary().toString(), getEntry());
}
}
then when the preferences activity starts, the current value is correctly interpolated into the summary. But when I click on the preference and select a different value from the dialog, when the dialog closes the summary still shows the now-old value. I need to close the preferences activity and restart it to see the change.
I've tried this in several emulators at different API levels. What do I need to so that the displayed summary always reflects the current value?
You could override "onDialogClosed" as below:
#override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
setSummary(getEntry());
}
}
This will set the summary of your preference to the text of the selected entry.
The original getSummary() in ListPreference only works when getEntries(), getEntryValues() and defaultValue are pre-populated when the Preference screen loads. So it works fine when you use a static fixed list of items, like a <string-array> resource.
But if you are dynamically generating the entries and entryValues at runtime, you need to ensure that these lists are generated when the Preference screen loads in onCreate() and also ensure that the defaultValue is set. Something like this:
SettingsFragment.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListPreference listPreference = (ListPreference) findPreference("dynamiclistItems");
CharSequence[] entryDisplayNames = new CharSequence[3];
entryDisplayNames[0] = "Item A";
entryDisplayNames[1] = "Item B";
entryDisplayNames[2] = "Item C";
CharSequence[] entryValues = new CharSequence[3];
entryValues[0] = "Item A Value";
entryValues[1] = "Item B Value";
entryValues[2] = "Item C Value";
listPreference.setEntries(entryDisplayNames);
listPreference.setEntryValues(entryValues);
if (listPreference.getValue() == null ||
listPreference.getValue().equals("")) {
// There is no stored string in shared prefs.
// The user has not chosen any value. So make
// the summary display a default entry "Item A"
// display name, which is item 0 in the 'entries' list. Info:
// https://stackoverflow.com/questions/5197228/how-to-set-the-default-value-of-a-listpreference
listPreference.setValueIndex(0);
}
}
For static lists that are populated with <string-array>, just ensure that android:defaultValue="..." is defined, and that it points to a valid item in the 'values' array. For example: android:defaultValue="Item A Value"
This will ensure that the android:summary="%s" will work properly for dynamically generated and static lists.