I am trying to programmatically delete one of the options in a list view from SharedPreferences. I have included simplified code below.
I have read through a ton of similar questions but it just will not seem to work for me. I must be misunderstanding a key concept. Please help.
I have tried using clear() and apply(). I have also tried adding an a line instead of deleting all without success.
I think I may be misunderstanding the concept of which keys to use and have tried alternates, but nothing seems to work.
my preferences.java
package il.preferences;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences preferences = getSharedPreferences(
"myKey", MODE_PRIVATE);
preferences.edit().remove("1").commit();
}
}
my preference.xml
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Cat X" >
<ListPreference
android:defaultValue="1"
android:entries="@array/myOptions"
android:entryValues="@array/myValues"
android:key="myKey"
android:summary="Select an item"
android:title="Choose" />
</PreferenceCategory>
</PreferenceScreen>
my strings.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<resources>
<string-array name="myOptions">
<item>A</item>
<item>B</item>
<item>C</item>
</string-array>
<string-array name="myValues">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
</resources>
My problem was that I conceptualised the preference framework wrong. I will share my wrong turns to help any other lost newbies.
I had confused the PreferenceScreen which I defined in my preferences.xml above and the file where the preferences are stored which can be seen on the DDMS perspective my.package.name_preferences.xml – use file manager – data – data – project name – shared_prefs to find and pull this file
I then incorrectly proceeded to try use the preference editor to alter the PreferenceScreen
Eventually I found the sample code in the Google APIs
com.example.android.apis.ApiDemos
com/example/android/apis/preference
which have all the permutations I needed, in order to finally understand.
my eventual solution was to use a combination of
setPreferenceScreen(createPreferenceHierarchy());
addPreferencesFromResource(R.xml.preferences);
to incorporate both my static and dynamic preferences. The code for my dynamic preferences I add below although, (thanks to Google). I recommend looking at the google api rather than trying to find tutorials online or using books.