Android Preference Activity, show edittext dialog when tap listview item - android

How to make a preference activity where contain listpreference, where the summary will change based on selected listpreference item, and when certain list item is taped, it will show a edit text dialog which it will also become the the summary string value.
Thank in advance.
as requested, here my current code
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_category_general"
android:key="pref_category_general">
<CheckBoxPreference
android:key="pref_debug_mode"
android:title="#string/pref_debug_mode"
android:summary="#string/pref_debug_mode_summary"
android:defaultValue="false" />
<ListPreference
android:dependency="pref_debug_mode"
android:key="pref_remotehost"
android:title="#string/pref_remotehost"
android:dialogTitle="#string/pref_remotehost_dialog_title"
android:entries="#array/pref_remotehost_entries"
android:entryValues="#array/pref_remotehost_entries_values"
android:defaultValue="#string/pref_remotehost_default" />
</PreferenceCategory>
</PreferenceScreen>
and my activity
public class SettingActivity extends SherlockPreferenceActivity implements View.OnClickListener {
private MainApplication G;
private SherlockPreferenceActivity me;
private Intent intent;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.G = ((MainApplication) getApplicationContext());
assert this.G != null;
super.onCreate(bundle);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Add a button to the header list.
if (hasHeaders()) {
Button button = new Button(this);
button.setText("Some action");
setListFooter(button);
button.setOnClickListener(this);
}
PreferenceFragment prefFragment = new PreferenceGeneralFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, prefFragment);
fragmentTransaction.commit();
this.intent = getIntent();
this.me = this;
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onClick(View v) {
/*
switch (element.getId()) {
default:
return;
case R.id.setting_cancel_config:
onBackPressed();
return;
case R.id.setting_save_config:
int i = this.modeSpinner.getSelectedItemPosition();
boolean flag = true;
if (i == 1) {
flag = false;
};
MainApplication.setDeveloperMode(flag);
MainApplication.setRemoteHost(this.remoteHostEdittext.getText().toString());
SettingActivity.this.finish();
onBackPressed();
return;
}
*/
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
/**
* This fragment shows the preferences for the first header.
*/
public static class PreferenceGeneralFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences_general, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_general);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
}
}
i don't know where to start

Related

Android can't figure out why perference screen won't show preference textbox

I'm trying to display preference screen and with a text box and doesn't show but in another screen it has no problem? It shows a negative 1 or null.
StatsActivity
public class StatsActivity extends Activity {
static final String TAG = "StatsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats_settings_layout);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
TextView settingsTextViewStats = (TextView) findViewById(R.id.stats_settings_text_view);
settingsTextViewStats.setText(builder.toString());
}
}
StatsPrefsActivity
public class StatsPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
static final String TAG = "StatsPrefsActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_stats);
PreferenceManager.setDefaultValues(this,R.xml.preferences_stats, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, StatsActivity.class));
return true;
}
return false;
}
#Override
public void onStart(){
super.onStart();
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(StatsPrefsActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
}
}
preference_stats.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings"
android:key="first_category">
<EditTextPreference
android:id="#+id/text_pref_box"
android:key="time_usage_key"
android:title="7 Day Usage"
android:summary="A total of usage of 7 days." />
</PreferenceCategory>
</PreferenceScreen>
if you want an inital value then set one. right now you have "-1" set as the default value. so if the preference has never been used before your going to get "-1" as the default. Try changing that to a blank string "" or something if you want better presentation.

Call onSharedPreferenceChanged() method from AlertDialog

I am Having an Alert Dialog which has a edit text box and a password box.
On pressing positive button of Alert Dialog I want to save data once entered in it to my Preference login_prefs,xml. Can anyone please help me to call onSharedPreferencesChanged method so that I can save my values in it.
I tried many ways but I failed to achieve it.
Also can any one help me to retrieve the default value from the same
Thanks
Code:
public class LoginCredsHandlerDialog extends SherlockDialogFragment {
String Tag = getClass().getSimpleName(), idString, passString , idKey = "loginId", passKey = "pass";
View view;
EditText id, pass;
SharedPreferences loginPrefs;
OnSharedPreferenceChangeListener listen;
final Context context = getSherlockActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder loginMenu = new AlertDialog.Builder(getSherlockActivity());
LayoutInflater inflate = getSherlockActivity().getLayoutInflater();
view = inflate.inflate(R.layout.prefs_layout, null);
loginMenu.setView(view);
id = (EditText) view.findViewById(R.id.loginId);
pass = (EditText) view.findViewById(R.id.loginPass);
Log.i(Tag, "before prefreneces class");
new SaveData();
loginPrefs = PreferenceManager.getDefaultSharedPreferences(getSherlockActivity());
Log.i(Tag, "linked to prefrences class");
Log.i(Tag, "Got String Value");
loginMenu.setTitle("Login Prefrences Menu");
loginMenu.setCancelable(false);
loginMenu.setPositiveButton("Save", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(Tag, "Save Key Pressed");
new SaveData().onSharedPreferenceChanged(loginPrefs, idKey);
Log.i(Tag, "Values Saved");
}
});
loginMenu.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
LoginCredsHandlerDialog.this.getDialog().cancel();
}
});
return loginMenu.create();
}
public class SaveData extends SherlockPreferenceActivity implements OnSharedPreferenceChangeListener {
SharedPreferences spf;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.log_prefs);
loginPrefs = PreferenceManager.getDefaultSharedPreferences(getSherlockActivity());
idString = loginPrefs.getString(idKey, "");
passString = loginPrefs.getString(passKey, "");
if(idString.equals("") || passString.equals("")){
idString = id.toString();
passString = pass.toString();
}
id.setText(idString);
pass.setText(passString);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key==idKey){
Log.i(Tag, "saver");
Preference pref = findPreference(key);
pref.setDefaultValue(sharedPreferences.getString(key, ""));
}
}
}
}
You do not call onSharedPreferencesChanged() function, it is call back function will be called when somebody change preference.
When you commit you login preference onSharedPreferencesChanged() will get called.
You can save value in preference like this:
loginPrefs.edit().putString("login_prefs", VALUE).commit();

show alert dialog when click item in listpreference-android

hello everyone i am new to android development.i want to open a alert dialog when user choose any theme in list preference in preference activity.i search lot in google but did not find any appropriate answer.here is my PrefenceActivity.
public class Setting extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Setting.setAppTheme(this);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
String ListPreference;
public static void setAppTheme(Activity a) {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(a);
int ListPreference = Integer.parseInt(prefs.getString("listPref", "3"));
if(ListPreference == 0) {
a.setTheme(R.style.AppBaseThemeDark);
return;
} else if(ListPreference == 1){
a.setTheme(R.style.AppBaseThemeLight);
//Toast.makeText(getApplicationContext(),"TTS Engines not found.\n Install TTS Engins",Toast.LENGTH_LONG).show();
} else if(ListPreference == 2){
a.setTheme(R.style.AppBaseTheme);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getActionBar().setDisplayHomeAsUpEnabled(true);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
getFragmentManager().popBackStack();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I faced the same problem a few days ago and I implemented a custom preference class extending ListPreference to do this. This is the class I implemented:
public class LogCleanPreference extends ListPreference {
private int mClickedDialogEntryIndex;
private Context mContext;
public LogCleanPreference(Context ctxt) {
this(ctxt, null);
}
public LogCleanPreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
mContext = ctxt;
setNegativeButtonText(ctxt.getString(R.string.alert_cancel));
}
#Override
protected void onPrepareDialogBuilder(Builder builder) {
if (getEntries() == null || getEntryValues() == null) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array.");
}
mClickedDialogEntryIndex = findIndexOfValue(getValue());
builder.setSingleChoiceItems(getEntries(), mClickedDialogEntryIndex,
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
// In my case I only show the AlertDialog if the user didn't select option number 2
if(which != 2){
// Show AlertDialog
}
else{
// Save preference and close dialog
mClickedDialogEntryIndex = which;
LogCleanPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
}
});
builder.setPositiveButton(null, null);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
CharSequence[] mEntryValues = getEntryValues();
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
}
}
}
}
This is how I use the preference in my prefs.xml:
<com.timeondriver.tod.settings.LogCleanPreference
android:defaultValue="0"
android:dialogTitle="#string/dialog_title_log_clean"
android:entries="#array/log_clean"
android:entryValues="#array/log_clean_values"
android:key="log_clean_preference"
android:summary="#string/summary_log_clean_preference"
android:title="#string/title_log_clean_preference" />
1st, Create a change listener:
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference
.setSummary(index >= 0 ? listPreference.getEntries()[index]
: null);
}
return true;
}
};
2nd, Bind preference to its value:
// Set the listener to watch for value changes.
preference
.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(
preference,
PreferenceManager.getDefaultSharedPreferences(
preference.getContext()).getString(preference.getKey(),
""));
3rd, in the 1st step you can insert the code to launch you dialog with the if condition.

preferencefragment no view found for id android

I had the getpreferencescreen deprecated so I tryed to implement the header preference activity.
here is my code:
public class EditPreferences extends PreferenceActivity {
ListPreference m_list_preference_dive_centre_rating;
ListPreference m_list_preference_dive_region_rating;
ListPreference m_list_preference_wreck;
ListPreference m_list_preference_cave;
MultyChoiceListPlugin m_list_preference_marine_life;
ListPreference m_list_preference_region;
Preference m_order_by_name;
SharedPreferences.Editor m_editor;
static Context m_context;
int m_order_type_val = 0;
boolean m_wreck_selected = false;
boolean m_cave_selected = false;
boolean m_marine_life_selected = false;
boolean m_region_selected = false;
int number_click_wreck = 0;
int number_click_cave = 0;
int number_click_marine_life = 0;
int number_click_region = 0;
boolean m_without_guide_selected = false;
boolean m_without_equipment_selected = false;
boolean m_budget_selected = false;
boolean m_region_rating = false;
boolean m_centre_rating = false;
private ListView m_preferenceView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//m_order_by_name.setOnPreferenceClickListener(onOrderByNamePrefClick);
final Button back_btn = (Button)this.findViewById(R.id.back);
final Button home_btn = (Button)this.findViewById(R.id.home);
//final Button search_btn = (Button)this.findViewById(R.id.search);
final Button info_btn = (Button)this.findViewById(R.id.info);
back_btn.setOnClickListener(onBackBtn);
home_btn.setOnClickListener(onHomeBtn);
// search_btn.setOnClickListener(onSearchBtn);
info_btn.setOnClickListener(onInfoBtn);
}
/**
* Populate the activity with the top-level headers.
*/
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.wrap_preferences);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.layout.wrap_preferences, false);
addPreferencesFromResource(R.xml.preferences1);
}
}
public static class Prefs2Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences2);
}
}
public static class Prefs3Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
// PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences3);
}
}
private View.OnClickListener onBackBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","last_from");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
private View.OnClickListener onHomeBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
//set the result to the callback of the parent activitie
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","home");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
I've got the error:No view found for id 0x1020343 (android:id/prefs) for fragment
XML code pref_headers.xml:
<?xml version="1.0" encoding="UTF-8"?>
<preference-headers
xmlns:android="http://schemas.android.com/apk/res/android" >
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs1Fragment"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs2Fragment"
android:title="#string/what_is_your_budget_text"
android:summary="#string/what_is_your_budget_summary" >
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs3Fragment"
android:title="#string/order_by_name_title"
android:summary="#string/order_by_name_summary">
</header>
<!-- <header
android:icon="#drawable/icon_question"
android:title="Blackmoon Info Tech Services"
android:summary="link to BITS blog">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.blackmoonit.com/2012/07/all_api_prefsactivity/" />
</header>
-->
XML code preferences1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
<PreferenceCategory
android:title="#string/who_is_the_best_dive_centre_text"
android:key="who_is_the_best_dive_centre_category">
<ListPreference
android:key="select_dive_centre_rating"
android:title="#string/select_dive_centre_rating_text"
android:summary="#string/select_dive_centre_rating_summary"
android:entries="#array/search_dive_centre_names"
android:entryValues="#array/search_dive_centre_clauses"
android:dialogTitle="#string/search_dive_centre_choice_title"/>
</PreferenceCategory>
</PreferenceScreen>
thanks in advance
The official documentation is misleading:
Removing the onCreate function in public class EditPreferences extends PreferenceActivity resolves the issue.
I just moved what was in onCreate to onBuildHeaders function.
I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.
The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().
You didn't show us your onCreate() method, so perhaps this is the same problem.

Android spinner refresh without using an OnItemSelectedListener

I have an issue I have been unable to figure out. I have a spinner loaded from an ArrayList saved in SharedPreferences. I allow the users to modify the spinner names through a PreferenceActivity in a separate class that is startActivityForResult. It works but I cannot for the life of me make the spinner refresh itself with the new name(s) unless the app is closed and then reopened.
When the user uses the back key to close the Edit names window the result code and result_ok information is passed back correctly. This is where I can't figure things out. I know I need to use NotifyDataSetChanged but I can't figure out how to do it since the modifications are made in a separate class and not in the OnItemSelectedListener like so many answers to questions here on StackOverflow suggest for refreshing spinner data.
Here is my spinner code:
private ArrayAdapter<String> adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
/* enable hardware acceleration on Android >= 3.0 */
final int FLAG_HARDWARE_ACCELERATED = WindowManager.LayoutParams.class
.getDeclaredField("FLAG_HARDWARE_ACCELERATED").getInt(null);
getWindow().setFlags(FLAG_HARDWARE_ACCELERATED,
FLAG_HARDWARE_ACCELERATED);
} catch (Exception e) {
}
checkPreferences();
setContentView(R.layout.main);
this.findViewById(R.id.label_mode).setOnClickListener(this);
this.findViewById(R.id.label_clear).setOnClickListener(this);
this.findViewById(R.id.label_data).setOnClickListener(this);
this.findViewById(R.id.label_wifi).setOnClickListener(this);
this.findViewById(R.id.label_roam).setOnClickListener(this);
this.findViewById(R.id.label_vpn).setOnClickListener(this);
this.findViewById(R.id.label_invert).setOnClickListener(this);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
// create the spinner
spinner = (Spinner) findViewById(R.id.spinner);
// profile names for spinner
final List<String> profilestring = new ArrayList<String>();
profilestring.add(prefs.getString("default",
getString(R.string.defaultprofile)));
profilestring.add(prefs.getString("profile1",
getString(R.string.profile1)));
profilestring.add(prefs.getString("profile2",
getString(R.string.profile2)));
profilestring.add(prefs.getString("profile3",
getString(R.string.profile3)));
profilestring.add(prefs.getString("profile4",
getString(R.string.profile4)));
profilestring.add(prefs.getString("profile5",
getString(R.string.profile5)));
profileposition = profilestring
.toArray(new String[profilestring.size()]);
// adapter for spinner
adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, profileposition);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
spinner.setSelection(prefs.getInt("itemPosition", 0));
spinner.post(new Runnable() {
public void run() {
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
int index = parent.getSelectedItemPosition();
if (index == 0) {
editor.putInt("itemPosition", index);
editor.commit();
LoadDefaultProfile();
}
if (index == 1) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile1();
}
if (index == 2) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile2();
}
if (index == 3) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile3();
}
if (index == 4) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile4();
}
if (index == 5) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile5();
}
}
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
});
I then set my selection and run the spinner with spinner.post(New Runnable).
My preference screen is very simple.
<?xml version="1.0" encoding="utf-8"?>
<EditTextPreference
android:key="default"
android:summary="Edit name for Default Profile"
android:title="#string/defaultprofile" />
<EditTextPreference
android:key="profile1"
android:summary="Edit name for profile1"
android:title="#string/profile1" />
<EditTextPreference
android:key="profile2"
android:summary="Edit name for profile2"
android:title="#string/profile2" />
<EditTextPreference
android:key="profile3"
android:summary="Edit name for profile3"
android:title="#string/profile3" />
<EditTextPreference
android:key="profile4"
android:summary="Edit name for profile4"
android:title="#string/profile4" />
<EditTextPreference
android:key="profile5"
android:summary="Edit name for profile5"
android:title="#string/profile5" />
EditNames class
public class EditProfileNames extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.prefs);
PreferenceManager.setDefaultValues(EditProfileNames.this,
R.layout.prefs, false);
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
resultOk();
}
return super.onKeyDown(keyCode, event);
}
/**
* Set the activity result to RESULT_OK and terminate this activity.
*/
private void resultOk() {
final Intent response = new Intent(Api.PREF_PROFILES);
setResult(RESULT_OK, response);
finish();
}
}
So what do I have to do to refresh the spinner? I know I could do it if the change was made in the OnItemSelectedListener but since it is an entirely different class that makes the changes I'm lost at the moment.
Thanks!
It sounds like you are passing a reference to your array, profileposition, to another class so that it can add elements to it. You will also need to pass a reference to adapter to that class as well, so that it can call adapter.notifyDataSetChanged(); after it has updated your array.
EDIT: Now that I see that you an Acitivty that you have started for a result is doing the updating of the array, you could just call adapter.notifyDataSetChanged(); in your onActivityResult() callback.
After changing the contents , call notifyDataSetChanged on the adapter and that will solve the issue.
Try this way
adapter.notifyDataSetChanged();

Categories

Resources