I have DialogPreference dialog instance. How can i register an listener on onDialogClosed. I want when Ok button is clicked to execute some code.
Is this possible to do with instance of DialogPreference ?
I know I can do it like
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
String text=MyEditText.getText();
}
else {
// cancel hit
}
}
but i am not extending DialogPreference. i have just instance of it.
Use preference.getDialog().setOnDismissListener(listener);
If you have the instance of DialogPreference, then you can impement onPreferenceChangedListener for the DialogPreference.
myDialogPreference
.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(
Preference preference) {
// Your code here
});
Related
Hi for me one doubt if I change any content or color of activity example, in activity1 I have one textview with data "apple" from shared preference. And I am clicking a button to start new activity2 there I am clicking one button to update the shared preference "apple" to "gova" I click back button of activity2 textview in activity should update. Is there any way to update without onResume() method or explain how onResume() working...?
onResume() is called every time your activity is shown to the user. Thus, if the user goes to another activity and then comes back to the first one, onResume() will be called. Your code should look like:
#Override
protected void onResume() {
super.onResume();
myTextView.setText(preferences.getString("myKey", "defaultValue");
}
If, for any reason, you'd prefer not to use onResume(), you can register a OnSharedPreferenceChangeListener, which will be called every time a shared pref value is changed.
Your first activity will include code that looks like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("myKey")) {
// update your textview
}
}
};
preferences.registerOnSharedPreferenceChangeListener(listener);
}
#Override
protected void onDestroy() {
super.onDestroy();
preferences.unregisterOnSharedPreferenceChangeListener(listener);
}
}
Just override onBackPressed method in second activity and in it set the value to shared preferences :
#Override
public void onBackPressed() {
// Set shared preference value
}
You should ideally use onBackPressed instead on onResume. Below is a code snippet on similar lines that should help
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really go back?")
.setMessage("Are you sure you want to?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Activity1.super.onBackPressed();
//change sharedPreferences here
}
}).create().show();
}
Hope this helps
I am tring to create a sharedpreference to save some authentication info to a third party service. In my preferences.xml there is a login and password fields but i would like to check if the values are valid (authenticate) when edited. What would be a good approach?
So far, i have this:
on create
findPreference("sync_service_enabled").setOnPreferenceChangeListener(this);
findPreference("sync_service_user").setOnPreferenceChangeListener(this);
findPreference("sync_service_pwd").setOnPreferenceChangeListener(this);
my listener
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference.getKey().contains("sync_service")){
new AuthenticationRemoteAsyncTask(this.getActivity(), user, password, service).execute();
}
return true;
I also need to save a token generated by the remote service so I need to wait for the aynstask to be finished.
Any sugestion?
I resolved my problem criating a custom dialogpreference. I Replaced the positive button onclicklistener so it dont close the dialog automatically and start my remote task. The asynctask will notify my preferencedialog after success and only then I close the dialog.
CODE
#Override
protected void showDialog(Bundle state) {
super.showDialog(state);
...
positiveButton.setOnClickListener(this);
negativeButton.setOnClickListener(this);
}
onclick handler
public void onClick(View view){
this.result = null;
if(view.getId() == positiveButton.getId()) {
String password = textPassword.getText().toString();
String user = textLogin.getText().toString();
new AuthenticationTask(getContext(),user, password)
.notify(this).execute();
}else{
alertDialog.dismiss();
}
}
check the result before close
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (result != null) {
SharedPreferences.Editor editor = getEditor();
editor.putString("sync_service_token",result);
editor.commit();
}
}
AuthenticationTask is a custom class that wrapp all the async stuff and call a notify method.
I have preference xml and following code:
public class MainActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getApplicationContext(), "DO SOMETHING", Toast.LENGTH_LONG).show();
}
}
I want to get notified over toast message, when one or more preferences are changed. I think upper code should work, but for some reason it doesn't.
I have for example CheckBoxPreference in my xml file. And when I check or uncheck CheckBox I want to be notified.
You have to set the listener like this for example:
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(this);
or, if You donĀ“t use the default shared preferences, You have to get Your prefs and then register them:
SharedPreferences preferences = getSharedPreferences("your_shared_prefs", Context.MODE_PRIVATE);
preferences.registerOnSharedPreferenceChangeListener(this);
You should register to listen to the shared preference changes:
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
I want to get value of a checkboxpreference. which method is suitable for listen to preference?
And what's real difference between OnPreferenceChangeListener and OnSharedPreferenceChangeListener ?!
UPDATE
Why onSharedPreferenceChanged not called?
public class Setting extends PreferenceActivity implements
OnSharedPreferenceChangeListener // ,OnPreferenceChangeListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);// deprecated warning
}
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {// DO Stuff
}
#Override
protected void onResume() {
super.onResume();
// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
// PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
this.getSharedPreferences("myPrefDB", MODE_PRIVATE)
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
// PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
this.getSharedPreferences("myPrefDB", MODE_PRIVATE)
.unregisterOnSharedPreferenceChangeListener(this);
}
}
The difference between these 2 is that OnPreferenceChangeListener is a callback called only when its preference changes (applies to a single key), while OnSharedPreferenceChange is a callback called whenever any of the preferences in that SharedPreferences object changes (applies to all keys).
So, in your case, you need to use the OnPreferenceChangeListener with your CheckBoxPreference.
Here is an example:
Preference ckboxPref = this.findPreference(CKBOX_PREF_KEY);
ckboxPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
//Do stuff
}
});
The method findPreference does not work if you use fragments, but you aren't using any so it is fine.
In my application I would like to set a click listener on the individual preferencelist items in my preference activity, the problem is I can only find out how to set a click listener on the just the main listprefernce itself, is there a way I could set a key to the individual list items so when I set up an OnPreferenceClickListener I can execute some list item specific code?
make sure your preference class implements OnPreferenceClickListener and then override the onPreferenceClick then just check what preference key was pressed
#Override
public boolean onPreferenceClick(Preference preference) {
if (preference.getKey().equals("schedulestart")) {
showDialog(0);
} else if (preference.getKey().equals("schedulestop")) {
showDialog(1);
} else if (preference.getKey().equals("priority")) {
getPreferenceManager().getSharedPreferences().edit().putInt("unreadcount", 0).commit();
}
return true;
}
This question is relatively ancient, but I was looking to do a similar thing -- specifically get a hook in whenever any ListPreference item is clicked. Things like onSharedPreferenceChanged did not work for me because I need to do something even when the currently selected ListPreference is clicked. I'm not sure I understand the other answer here as solving the problem. My googling hasn't uncovered any other solutions.
I went along with extending ListPreference and overriding onDialogClosed(). The ListPreference source code for onDialogClosed is
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
}
}
}
I created a working interface to send the value of the selected list item in my new ListPreference and then overrode onDialogClosed:
public class MyListPreference extends ListPreference {
private ListItemClickListener mListItemClickListener;
...
public void setOnListItemClickListener(ListItemClickListener listener) {
mListItemClickListener = listener;
}
public interface ListItemClickListener {
public void onListItemClick(String value);
}
...
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && getEntryValues() != null && mListItemClickListener != null) {
String value = getValue();
mListItemClickListener.onListItemClick(value);
}
}
Then, in your settings activity (or wherever you are using the new ListPreference), just hook it in:
#Override
protected void onResume() {
super.onResume();
MyListPreference listPref = (MyListPreference)
findPreference(getString(R.string.key_name));
listPref.setOnListItemClickListener(this);
}
...
public void onListItemClick(String value) {
// Do something
}
This works for my purposes.