4

I am trying to make dialog preference in preferences, where user just click positive button to trigger some action. (Clear database? No | Yes)

public class MyDialogPreference extends DialogPreference {

    public MyDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        Log.d(MainActivity.TAG, "# onDialogClosed: " + positiveResult);
    }

}

I dont actually want to persist anything, just trigger onSharedPreferenceChanged listener, so I can handle it in the activity. But I cant figure out how to trigger it

//SOLUTION

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);
    if(positiveResult) {
        persistBoolean(!getPersistedBoolean(true));
    }
    Log.d(MainActivity.TAG, "# onDialogClosed: " + positiveResult);
}
urSus
  • 12,492
  • 12
  • 69
  • 89
  • Maybe call `notifyChanged()` or `callChangeListener()`in your `onDialogClosed()`? I think callChangeListener is what you need. – A--C Dec 13 '12 at 01:35
  • I tried that as first, It doesnt work -.- – urSus Dec 13 '12 at 01:45
  • May I know why must use persistBoolean? Can we use other like persistLong... – Cheok Yan Cheng May 30 '13 at 17:49
  • 1
    @CheokYanCheng its doesnt matter, you can use long, boolean is just "handy" because you can "toggle" true false with ! operator to always trigger the listener and dont worry about it – urSus May 31 '13 at 03:19

1 Answers1

5

onSharedPreferenceChanged is called because of the inbuilt callback registered on the sharedpreference, so unless you change the key associated with dialogPreference you are not going to get the onSharedPreferenceChanged callback.

So what you could do is everytime dialog is closed, you could change the value in key. Something like below

text = getPersistedString("1")
if(text.length() > 10)
   text = "1";
persistString(text+"1");

Make sure your dialogPreference has a key and android:persistent as true in xml

nandeesh
  • 24,740
  • 6
  • 69
  • 79