Android PreferenceManager.setDefaultValues() crashes with class cast exception - android

I have a frustrating problem, I have created a custom preference for Android, using the support library.
public class CustomTimePreference extends DialogPreference {
public int hour = 0;
public int minute = 0;
public CustomTimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public static int parseHour(String value) {
try {
String[] time = value.split(":");
return (Integer.parseInt(time[0]));
} catch (Exception e) {
return 0;
}
}
public static int parseMinute(String value) {
try {
String[] time = value.split(":");
return (Integer.parseInt(time[1]));
} catch (Exception e) {
return 0;
}
}
public static String timeToString(int h, int m) {
return String.format("%02d", h) + ":" + String.format("%02d", m);
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String value;
if (restoreValue) {
if (defaultValue == null) value = getPersistedString("00:00");
else value = getPersistedString(defaultValue.toString());
} else {
value = defaultValue.toString();
}
hour = parseHour(value);
minute = parseMinute(value);
}
public void persistStringValue(String value) {
persistString(value);
}
}
and
public class CustomTimePreferenceDialogFragmentCompat extends PreferenceDialogFragmentCompat implements DialogPreference.TargetFragment {
TimePicker timePicker = null;
#Override
protected View onCreateDialogView(Context context) {
timePicker = new TimePicker(context);
return (timePicker);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
timePicker.setIs24HourView(true);
CustomTimePreference pref = (CustomTimePreference) getPreference();
timePicker.setCurrentHour(pref.hour);
timePicker.setCurrentMinute(pref.minute);
}
#Override
public void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
CustomTimePreference pref = (CustomTimePreference) getPreference();
pref.hour = timePicker.getCurrentHour();
pref.minute = timePicker.getCurrentMinute();
String value = CustomTimePreference.timeToString(pref.hour, pref.minute);
if (pref.callChangeListener(value)) pref.persistStringValue(value);
}
}
#Override
public Preference findPreference(CharSequence charSequence) {
return getPreference();
}
}
For completeness, the xml contained within the preferences.xml is:
<customcontrols.CustomTimePreference
android:key="time_pace_preference"
android:title="#string/title_time_pace_preference"
android:defaultValue="#string/settings_default_pace"
android:summary="Set some time"
/>
However, when I attempt to call
PreferenceManager.setDefaultValues(mContext, preferences, true);
I receive
java.lang.ClassCastException: customcontrols.CustomTimePreference cannot be cast to android.preference.Preference
Why is this happening? as CustomTimePreference extends DialogPreference which itself extends Preference, this should be fine?!
If I don't call the setDefaultValues() I am able to go into my settings fragment and view the custom control?
What am I doing wrong, and how do I fix it!?

If you are extending android.support.v7.preference.DialogPreference that will cause this crash.
If so, you can use android.support.v7.preference.PreferenceManager#setDefaultValues(android.content.Context, int, boolean) instead.

Related

Android DialogPreference: Cannot resolve method 'registerOnActivityDestroyListener(android.preference.DialogPreference)

I've created a custom preferencedialog that I'm trying to open whenever a switchpreference is set to on.
SettingsFragment:
...
#PreferenceChange(R.string.activity_settings_sync_key)
void syncPreferenceChanged(boolean newValue, Preference preference) {
if (newValue) {
// Show preferencedialog
SyncPreference syncpreference = new SyncPreference(getActivity(), null);
syncpreference.show();
} else {
return;
}
}
...
When I run the app and switch on the switchpreference I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.preference.PreferenceManager.registerOnActivityDestroyListener(
android.preference.PreferenceManager$OnActivityDestroyListener)'
on a null object reference
at android.preference.DialogPreference.showDialog(DialogPreference.java:305)
at com.conhea.smartgfr.preferences.SyncPreference.show(SyncPreference.java:76)
at com.conhea.smartgfr.preferences.SettingsFragment.syncPreferenceChanged(SettingsFragment.java:53)
at com.conhea.smartgfr.preferences.SettingsFragment_$1.onPreferenceChange(SettingsFragment_.java:84)
at android.preference.Preference.callChangeListener(Preference.java:928)
at android.preference.TwoStatePreference.onClick(TwoStatePreference.java:64)
at android.preference.Preference.performClick(Preference.java:983)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:214)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
...
When I open the Android DialogPreference class the problem is related to the showDialog method, which cannot resolve the method registerOnActivityDestroyListener():
It looks as if registerOnActivityDestroyListener doesn't exist in the PreferenceManager class, but I can find it in the Android sourcecode:
/**
* Registers a listener.
*
* #see OnActivityDestroyListener
*/
void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {
synchronized (this) {
if (mActivityDestroyListeners == null) {
mActivityDestroyListeners = new ArrayList<OnActivityDestroyListener>();
}
if (!mActivityDestroyListeners.contains(listener)) {
mActivityDestroyListeners.add(listener);
}
}
}
Does anyone know what to do here?
Update 1
SyncPreference.java:
public class SyncPreference extends DialogPreference {
private EditText mHostText, mPortText;
private String mHost;
private int mPort;
private final int mDialogLayoutResId = R.layout.dialog_settings_server_preferences;
private SharedPreferences mSharedPreferences;
public SyncPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setDialogLayoutResource(mDialogLayoutResId);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
}
#Override
public int getDialogLayoutResource() {
return mDialogLayoutResId;
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
mHostText = (EditText) view.findViewById(R.id.dialog_settings_server_host_ip);
mPortText = (EditText) view.findViewById(R.id.dialog_settings_server_port);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
// Restore existing state
mHostText.setText(getHost());
mPortText.setText(String.valueOf(getPort()));
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
setHost(mHostText.getText().toString());
setPort(Integer.valueOf(mPortText.getText().toString()));
}
}
public void show() {
showDialog(null);
}
private String getHost() {
return getSharedPreferences().getString(
getContext().getString(R.string.activity_settings_server_host_ip_key),
getContext()
.getString(R.string.activity_settings_server_host_ip_default));
}
private int getPort() {
return getSharedPreferences().getInt(
getContext().getString(R.string.activity_settings_server_port_key),
Integer.valueOf(getContext()
.getString(R.string.activity_settings_server_port_default)));
}
private void setHost(String host) {
this.mHost = host;
getSharedPreferences().edit().putString(
getContext().getString(R.string.activity_settings_server_host_ip_key),
host).apply();
}
private void setPort(int port) {
this.mPort = port;
getSharedPreferences().edit().putInt(
getContext().getString(R.string.activity_settings_server_port_key),
port).apply();
}
}

Custom preference isPersistent()

I wrote my own number picker preference using android's brief guide and some googling. My question is regarding the onSaveInstanceState() method. On google's tutorial, it is suggested that we use the method isPersistent() to determine if the preference is persistent and if it is, then just return the superstate. I didn't do that because with this condition, if I swipe the number picker to a new number and then rotate the screen, the rotated version will return back to the persisted value. If I remove this condition then everything is ok. However, checking the source code of other preferences, like edittextpreference, this condition exists and the state is saved even if I change the value to an unsaved one and then rotate the screen.. Can somebody explain that please?
Here is my code:
public class NumberPreference extends DialogPreference {
private final static int DEFAULT_VALUE=R.integer.timer_def;
private final static int DEFAULT_MIN_VALUE=R.integer.timer_min_def;
private final static int DEFAULT_MAX_VALUE=R.integer.timer_max_def;
private final int min;
private final int max;
private final String time;
private int timer;
private NumberPicker numberPicker;
public NumberPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.number_preference);
setNegativeButtonText("Cancel");
setPositiveButtonText("OK");
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.number_preference, 0, 0);
try{
min=a.getInteger(R.styleable.number_preference_min, DEFAULT_MIN_VALUE);
max=a.getInteger(R.styleable.number_preference_max, DEFAULT_MAX_VALUE);
time=a.getString(R.styleable.number_preference_time);
}finally{
a.recycle();
}
setDialogIcon(null);
}
public void setSummary() {
super.setSummary("Every "+getTimer()+' '+time);
}
#Override
protected View onCreateView(ViewGroup parent) {
setSummary();
return super.onCreateView(parent);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
int number = numberPicker.getValue();
if (callChangeListener(number)){
timer=number;
persistInt(timer);
setSummary();
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInt(index,DEFAULT_VALUE);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
timer = getPersistedInt(DEFAULT_VALUE);
}
else{
timer =(Integer) defaultValue;
persistInt(timer);
}
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
numberPicker=(NumberPicker) view.findViewById(R.id.numpref_picker);
numberPicker.setMinValue(min);
numberPicker.setMaxValue(max);
numberPicker.setValue(timer);
}
public int getTimer() {
return getPersistedInt(DEFAULT_VALUE);
}
#Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
return superState;
}
final SavedState myState=new SavedState(superState);
if (numberPicker!= null) myState.value=numberPicker.getValue();
return myState;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (state==null || !state.getClass().equals(SavedState.class)){
super.onRestoreInstanceState(state);
return;
}
SavedState myState=(SavedState)state;
super.onRestoreInstanceState(myState.getSuperState());
if (numberPicker!=null)numberPicker.setValue(myState.value);
}
private static class SavedState extends BaseSavedState {
// field that holds the setting's value
int value;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
// Get the current preference's value
value = source.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
// Write the preference's value
dest.writeInt(value);
}
// Standard creator object using an instance of this class
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
Thanks:)
without having tested it, would assume you might have to change
private final String time;
to
private String time;
and pass String.valueOf(time) as an argument into the .setSummary() method. of course, the occurrence in .onCreateView() would need to pass the value read from the preferences - or the default value as fallback, if nothing had been returned. try to make in more simple, than more complex.

Default value of custom DialogPreference is null

I have a TimePreference class that derives from DialogPreference. I'm using 3 NumberPicker to set hours, minutes and seconds. This works fine. But when onSetInitialValue is called defaultValue is always null. Whereas onGetDefaultValue returns the correct value that is defined in the preferences. Any ideas what is wrong?
public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) {
super(ctxt, attrs, defStyle);
setPositiveButtonText(R.string.ok);
setNegativeButtonText(R.string.cancel);
setDialogLayoutResource(R.layout.time_preference_layout);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
mHoursPicker = (NumberPicker)v.findViewById(R.id.hours);
mHoursPicker.setMinValue(0);
mHoursPicker.setMaxValue(23);
mHoursPicker.setFormatter(TWO_DIGIT_FORMATTER);
mMinutesPicker = (NumberPicker)v.findViewById(R.id.minutes);
mMinutesPicker.setMinValue(0);
mMinutesPicker.setMaxValue(59);
mMinutesPicker.setFormatter(TWO_DIGIT_FORMATTER);
mSecondsPicker = (NumberPicker)v.findViewById(R.id.seconds);
mSecondsPicker.setMinValue(0);
mSecondsPicker.setMaxValue(59);
mSecondsPicker.setFormatter(TWO_DIGIT_FORMATTER);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
long currentTimeInMillis = convertTimeToMillis();
if (callChangeListener(currentTimeInMillis)) {
persistLong(currentTimeInMillis);
notifyChanged();
}
}
CharSequence summary = getSummary();
setSummary(summary);
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
super.onGetDefaultValue(a, index);
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
super.onSetInitialValue(restoreValue, defaultValue);
long value = 0;
if (restoreValue) {
if (defaultValue == null) {
Log.d( "bla", "No default value defined!");
} else {
value = Long.parseLong(getPersistedString((String) defaultValue));
}
} else {
if (defaultValue == null) {
Log.d( "bla", "No default value defined!");
} else {
value = Long.parseLong((String) defaultValue);
}
}
String result = convertMillisToTime(value);
setSummary(result);
}
#Override
public CharSequence getSummary() {
if (mHoursPicker == null) {
return null;
}
return convertTimeToString( mHoursPicker.getValue(), mMinutesPicker.getValue(), mSecondsPicker.getValue());
}
}
Why don't you try setting the default value manually? If you are saving this time value to sharedPreferences, you can specify it in your xml declaration of a PreferenceScreen:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<PreferenceCategory
android:title="#string/pref_cat_general"
android:layout_width="match_parent"
android:layout_height="match_parent">
<to.marcus.rxtesting.ui.widgets.ChoicePreference
android:key="#string/pref_key_sel_time"
android:title="#string/pref_title_time"
android:summary="set time"/>
Notice the custom preference ChoicePreference. Once this is declared, you can define it in its own class, similarly to what you've done above by extending DialogPreference:
public class ChoicePreference extends DialogPreference {
public ChoicePreference(Context context, AttributeSet attrs){
super(context,attrs);
}
#Override
protected void onClick(){
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setTitle("Check Time");
dialog.setMessage("confirm time:");
dialog.setCancelable(true);
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "time set!", Toast.LENGTH_SHORT).show();
putPrefValue("key_sel_time",true);
}
});
The putPrefValue(key,value) method will write/overwrite your sharedPreference value:
private void putPrefValue(String key, boolean value){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = prefs.edit();
//removes existing key to trigger change listener
editor.remove(key);
editor.commit();
editor.putBoolean(key, value);
editor.apply();
}
Then from this point you'll need your Activity, for instance, to listen to these sharedPreference changes:
1.) set a listener variable for your sharedPrefs:
private static SharedPreferences sharedPrefs;
private static SharedPreferences.OnSharedPreferenceChangeListener mListener;
2.) register/unregister the listener
#Override
protected void onResume() {
super.onResume();
sharedPrefs.registerOnSharedPreferenceChangeListener(mListener);
}
#Override
protected void onPause() {
super.onPause();
sharedPrefs.unregisterOnSharedPreferenceChangeListener(mListener);
}
3.) get an instance and do something with the result/change
private void initSharedPrefsListener(){
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key){
mBasePresenterImpl.onPrefSelected(key, sharedPrefs.getString(key, "default value here"));
}
};
}
The onPrefSelected method here is conceptual. You can could take the resulting value and persist it to a JsonString.

Android DialogPreference NullPointerException in onRestoreInstanceState

I am trying to implement a DialogPreference with two NumberPicker objects, that restores the last changed NumberPicker values after orientation change:
public class CustomTimePreference extends DialogPreference {
public NumberPicker firstPicker, secondPicker;
private int lastHour = 0;
private int lastMinute = 15;
private int firstMaxValue;
private int tempHour;
private int tempMinute;
private int rotatedHour;
private int rotatedMinute;
private int firstMinValue = 0;
private int secondMinValue=0;
private int secondMaxValue=59;
private String headerText;
private boolean usedForApprox;
public static int getHour(String time){
String[] pieces = time.split(":");
return (Integer.parseInt(pieces[0]));
}
public static int getMinute(String time){
String[] pieces = time.split(":");
return (Integer.parseInt(pieces[1]));
}
public CustomTimePreference(Context context){
this(context, null);
}
public CustomTimePreference(Context context, AttributeSet attrs){
super(context, attrs);
init(attrs);
setDialogLayoutResource(R.layout.custom_time_preference);
setPositiveButtonText(context.getString(R.string.time_preference_set_text));
setNegativeButtonText(context.getString(R.string.time_preference_cancel_text));
}
private void init(AttributeSet attrs){
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTimePreference);
firstMaxValue = a.getInteger(R.styleable.CustomTimePreference_firstMaxValue,10);
usedForApprox = a.getBoolean(R.styleable.CustomTimePreference_usedForApproximate, false);
headerText = a.getString(R.styleable.CustomTimePreference_customTimeDialogTopText);
a.recycle();
}
public void setFirstPickerValue(int value){
firstPicker.setValue(value);
}
public void setSecondPickerValue(int value){
secondPicker.setValue(value);
}
#Override
protected View onCreateDialogView(){
Log.d("OnCreateDialogView","nanana");
View root = super.onCreateDialogView();
TextView tv = (TextView)root.findViewById(R.id.custom_time_preference_title);
tv.setText(headerText);
firstPicker = (NumberPicker)root.findViewById(R.id.time_preference_first_picker);
firstPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
tempHour = newVal;
}
});
secondPicker = (NumberPicker)root.findViewById(R.id.time_preference_second_picker);
secondPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
tempMinute = newVal;
}
});
if(usedForApprox){
int smallestValue = MainActivity.getShortestPeriodLength(getContext());
int second = smallestValue % 60;
second-=1;
firstPicker.setMaxValue(second);
secondPicker.setMaxValue(59);
} else {
firstPicker.setMaxValue(firstMaxValue);
secondPicker.setMaxValue(secondMaxValue);
}
firstPicker.setMinValue(firstMinValue);
secondPicker.setMinValue(secondMinValue);
return root;
}
#Override
protected void onBindDialogView(View v){
super.onBindDialogView(v);
firstPicker.setValue(lastHour);
secondPicker.setValue(lastMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult){
super.onDialogClosed(positiveResult);
if(positiveResult){
lastHour = firstPicker.getValue();
lastMinute = secondPicker.getValue();
if (lastHour ==0 && lastMinute == 0){
lastMinute =1;
}
String time = String.valueOf(lastHour) + ":" + String.valueOf(lastMinute);
if(callChangeListener(time)){
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index){
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue){
String time = null;
if(restoreValue){
if (defaultValue == null){
time = getPersistedString("00:00");
} else {
time = getPersistedString(defaultValue.toString());
}
} else {
time = defaultValue.toString();
}
lastHour = tempHour = getHour(time);
lastMinute = tempMinute = getMinute(time);
}
private static class SavedState extends BaseSavedState {
// Member that holds the setting's value
// Change this data type to match the type saved by your Preference
String value;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
// Get the current preference's value
value = source.readString(); // Change this to read the appropriate data type
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
// Write the preference's value
dest.writeString(value); // Change this to write the appropriate data type
}
// Standard creator object using an instance of this class
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
#Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
// Check whether this Preference is persistent (continually saved)
/*
if (isPersistent()) {
// No need to save instance state since it's persistent, use superclass state
return superState;
}
*/
// Create instance of custom BaseSavedState
final SavedState myState = new SavedState(superState);
// Set the state's value with the class member that holds current setting value
myState.value = String.valueOf(tempHour) + ":" + String.valueOf(tempMinute);
return myState;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
// Check whether we saved the state in onSaveInstanceState
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save the state, so call superclass
super.onRestoreInstanceState(state);
return;
}
// Cast state to custom BaseSavedState and pass to superclass
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
// Set this Preference's widget to reflect the restored state
rotatedHour = getHour(myState.value);
rotatedMinute = getMinute(myState.value);
firstPicker.setValue(rotatedHour);
secondPicker.setValue(rotatedMinute);
}
}
There are two problems:
The app crashes, when i open my custom preference, change values on one of the pickers, and then rotate the phone from portrait to landscape. The error is NuLLpointerException and it points to the line where i try to assing the restored value to one of my NumberPicker objects.
This is more a question than a problem. I copied the BaseSavedState inner class and both onSaveInstanceState(), onRestoreInstanceState() functions from Android Developer homepage, but when i tried the app to restore values on orientation change, the phone showed the persisted values, not the latest values before orientation change. When i tried to examine the code with log messages, i discovered that my phone on SaveInstanceState isPersisted check exits the function and doesn`t operate with BaseSavedState object att all. I comented out that isPersisted check so now i can save and retrieve values from BaseSavedState object, but after that the problem nr. 1 appears. So my question is, what is the reasoning to skip the BaseSavedState object creation, if the preference is persistent. And is my decision to skip the persistent check and force the app to create BaseSavedState object a bad one?
Take a look at this implementation with 3 NumberPicker objects:
package com.bom.dom;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
public class TimePreference extends DialogPreference {
NumberPicker hoursNumberPicker;
NumberPicker minutesNumberPicker;
NumberPicker secondsNumberPicker;
int time;
int currentTime;
public TimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onBindDialogView(View view) {
hoursNumberPicker = (NumberPicker) view.findViewById(R.id.numberpicker_hours);
hoursNumberPicker.setMaxValue(24);
hoursNumberPicker.setMinValue(0);
hoursNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
updateCurrentTimeFromUI();
}
});
minutesNumberPicker = (NumberPicker) view.findViewById(R.id.numberpicker_minutes);
minutesNumberPicker.setMaxValue(59);
minutesNumberPicker.setMinValue(0);
minutesNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
updateCurrentTimeFromUI();
}
});
secondsNumberPicker = (NumberPicker) view.findViewById(R.id.numberpicker_seconds);
secondsNumberPicker.setMaxValue(59);
secondsNumberPicker.setMinValue(0);
secondsNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
updateCurrentTimeFromUI();
}
});
updateUI();
super.onBindDialogView(view);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
time = currentTime;
persistInt(time);
return;
}
currentTime = time;
}
private void updateCurrentTimeFromUI() {
int hours = hoursNumberPicker.getValue();
int minutes = minutesNumberPicker.getValue();
int seconds = secondsNumberPicker.getValue();
currentTime = hours * 3600 + minutes * 60 + seconds;
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
time = getPersistedInt(1);
} else {
time = (Integer) defaultValue;
persistInt(time);
}
currentTime = time;
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
Integer defaultValue = a.getInteger(index, 1);
return defaultValue;
}
private void updateUI() {
int hours = (int) (currentTime / 3600);
int minutes = ((int) (currentTime / 60)) % 60;
int seconds = currentTime % 60;
hoursNumberPicker.setValue(hours);
minutesNumberPicker.setValue(minutes);
secondsNumberPicker.setValue(seconds);
}
#Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
final SavedState myState = new SavedState(superState);
myState.value = currentTime;
return myState;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
currentTime = myState.value;
super.onRestoreInstanceState(myState.getSuperState());
}
private static class SavedState extends BaseSavedState {
int value;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
value = source.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(value);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
The layout file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<NumberPicker
android:id="#+id/numberpicker_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<NumberPicker
android:id="#+id/numberpicker_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<NumberPicker
android:id="#+id/numberpicker_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I found the solution on first problem:
To avoid the NullPointerException, i had to enclose the functions, that access NumberPicker objects, with a check, that determines if those pickers are initiated. I had this problem because on my app i have multiple my custom preference instances, and when i tried to follow the data path for saving/restoring functions, i discovered, that in logcat i had twice the amount of my own messages (not only for my onscreen preference, but also for the other prefrerence that uses my custom DialogPreference class). And because, i opened only one preference, the initialisation of NumberPicker objects in other preference didn`t happened, so accessing those pickers led (if i understood correctly) to NullPointerException.
But i still would like to hear someone more experienced, that could explain the default behaviour with save/restore functions.

TimePicker in PreferenceScreen

I'd like to create a preference field called Interval and I want to be able to popup a TimePicker and set a mm:ss formated value with minimal value 00:30 and step 30 seconds.
Is it possible to use TimePicker in PreferenceScreen ?
There is no TimePreference built into Android. However, creating your own is fairly easy. Here's one I did:
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class TimePreference extends DialogPreference {
private int lastHour=0;
private int lastMinute=0;
private TimePicker picker=null;
public static int getHour(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[0]));
}
public static int getMinute(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[1]));
}
public TimePreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
#Override
protected View onCreateDialogView() {
picker=new TimePicker(getContext());
return(picker);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time=null;
if (restoreValue) {
if (defaultValue==null) {
time=getPersistedString("00:00");
}
else {
time=getPersistedString(defaultValue.toString());
}
}
else {
time=defaultValue.toString();
}
lastHour=getHour(time);
lastMinute=getMinute(time);
}
}
I have modified the code from first answer:
it stores selected time in long form (milliseconds) which is easier to work with (using Calendar) then string
it automatically shows selected time in summary field in user's format (12 or 24 hour)
Updated code:
public class TimePreference extends DialogPreference {
private Calendar calendar;
private TimePicker picker = null;
public TimePreference(Context ctxt) {
this(ctxt, null);
}
public TimePreference(Context ctxt, AttributeSet attrs) {
this(ctxt, attrs, android.R.attr.dialogPreferenceStyle);
}
public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) {
super(ctxt, attrs, defStyle);
setPositiveButtonText(R.string.set);
setNegativeButtonText(R.string.cancel);
calendar = new GregorianCalendar();
}
#Override
protected View onCreateDialogView() {
picker = new TimePicker(getContext());
return (picker);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(calendar.get(Calendar.MINUTE));
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
calendar.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
calendar.set(Calendar.MINUTE, picker.getCurrentMinute());
setSummary(getSummary());
if (callChangeListener(calendar.getTimeInMillis())) {
persistLong(calendar.getTimeInMillis());
notifyChanged();
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return (a.getString(index));
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
if (defaultValue == null) {
calendar.setTimeInMillis(getPersistedLong(System.currentTimeMillis()));
} else {
calendar.setTimeInMillis(Long.parseLong(getPersistedString((String) defaultValue)));
}
} else {
if (defaultValue == null) {
calendar.setTimeInMillis(System.currentTimeMillis());
} else {
calendar.setTimeInMillis(Long.parseLong((String) defaultValue));
}
}
setSummary(getSummary());
}
#Override
public CharSequence getSummary() {
if (calendar == null) {
return null;
}
return DateFormat.getTimeFormat(getContext()).format(new Date(calendar.getTimeInMillis()));
}
}
For those whom the implementation of a custom Preference isn't so obvious (like it wasn't for me), you have to add this to your preferences.xml or whatever you're calling it.
You'll end up with something like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="editTextPref_Key"
android:title="#string/editTextPref_title"/>
<com.example.myapp.TimePreference
android:key="timePrefA_Key"
android:title="#string/timePrefA_title"/>
<com.example.myapp.TimePreference
android:key="timePrefB_Key"
android:title="#string/timePrefB_title"/>
</PreferenceScreen>
Assuming you added the TimePreference to your own root package:
(src/com/example/myapp/TimePreference.java)
For Preferences Support Library different code is needed. It requires two custom classes TimePreference and TimePreferenceDialogFragmentCompat, as well as overide of onDisplayPreferenceDialog method in PreferenceFragmentCompat extension class.
TimePreference.java
package com.test;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.preference.DialogPreference;
import android.util.AttributeSet;
public class TimePreference extends DialogPreference
{
public int hour = 0;
public int minute = 0;
public static int parseHour(String value)
{
try
{
String[] time = value.split(":");
return (Integer.parseInt(time[0]));
}
catch (Exception e)
{
return 0;
}
}
public static int parseMinute(String value)
{
try
{
String[] time = value.split(":");
return (Integer.parseInt(time[1]));
}
catch (Exception e)
{
return 0;
}
}
public static String timeToString(int h, int m)
{
return String.format("%02d", h) + ":" + String.format("%02d", m);
}
public TimePreference(Context context, AttributeSet attrs)
{
super(context, attrs);
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index)
{
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue)
{
String value;
if (restoreValue)
{
if (defaultValue == null) value = getPersistedString("00:00");
else value = getPersistedString(defaultValue.toString());
}
else
{
value = defaultValue.toString();
}
hour = parseHour(value);
minute = parseMinute(value);
}
public void persistStringValue(String value)
{
persistString(value);
}
}
TimePreferenceDialogFragmentCompat.java
package com.test;
import android.content.Context;
import android.support.v7.preference.DialogPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceDialogFragmentCompat;
import android.view.View;
import android.widget.TimePicker;
public class TimePreferenceDialogFragmentCompat extends PreferenceDialogFragmentCompat implements DialogPreference.TargetFragment
{
TimePicker timePicker = null;
#Override
protected View onCreateDialogView(Context context)
{
timePicker = new TimePicker(context);
return (timePicker);
}
#Override
protected void onBindDialogView(View v)
{
super.onBindDialogView(v);
timePicker.setIs24HourView(true);
TimePreference pref = (TimePreference) getPreference();
timePicker.setCurrentHour(pref.hour);
timePicker.setCurrentMinute(pref.minute);
}
#Override
public void onDialogClosed(boolean positiveResult)
{
if (positiveResult)
{
TimePreference pref = (TimePreference) getPreference();
pref.hour = timePicker.getCurrentHour();
pref.minute = timePicker.getCurrentMinute();
String value = TimePreference.timeToString(pref.hour, pref.minute);
if (pref.callChangeListener(value)) pref.persistStringValue(value);
}
}
#Override
public Preference findPreference(CharSequence charSequence)
{
return getPreference();
}
}
Required modifications in PreferenceFragmentCompat extension class
public static class PreferencesFragment extends PreferenceFragmentCompat
{
....
#Override
public void onDisplayPreferenceDialog(Preference preference)
{
DialogFragment dialogFragment = null;
if (preference instanceof TimePreference)
{
dialogFragment = new TimePreferenceDialogFragmentCompat();
Bundle bundle = new Bundle(1);
bundle.putString("key", preference.getKey());
dialogFragment.setArguments(bundle);
}
if (dialogFragment != null)
{
dialogFragment.setTargetFragment(this, 0);
dialogFragment.show(this.getFragmentManager(), "android.support.v7.preference.PreferenceFragment.DIALOG");
}
else
{
super.onDisplayPreferenceDialog(preference);
}
}
}
With above code time preference can be used in preferences xml file like this
<com.test.TimePreference
android:key="some_time"
android:title="Set some time"
android:defaultValue="12:00"
android:summary="Set some time"/>
CommonsWare's solution has a few problems, which I fixed:
It doesn't update the field properly after it is changed
The minutes value only persists a single digit, e.g. 10:2 instead of 10:02
If you use PreferenceManager.setDefaultPreferences to set initial default preferences in your app, it won't work because onSetInitialValue needs to persist it
The formatting of the result isn't tailored to the user's Locale (e.g. US uses AM/PM)
Here's my code, enjoy.
public class TimePreference extends DialogPreference {
private int lastHour=0;
private int lastMinute=0;
private TimePicker picker=null;
public static int getHour(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[0]));
}
public static int getMinute(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[1]));
}
public TimePreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
#Override
protected View onCreateDialogView() {
picker=new TimePicker(getContext());
return(picker);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
setSummary(getSummary());
String lastMinuteString = String.valueOf(lastMinute);
String time = String.valueOf(lastHour) + ":" + (lastMinuteString.length() == 1 ? "0" + lastMinuteString : lastMinuteString);
if (callChangeListener(time)) {
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time;
String defaultValueStr = (defaultValue != null) ? defaultValue.toString() : "00:00";
if (restoreValue)
time = getPersistedString(defaultValueStr);
else {
time = defaultValueStr;
if (shouldPersist())
persistString(defaultValueStr);
}
lastHour=getHour(time);
lastMinute=getMinute(time);
setSummary(getSummary());
}
#Override
public CharSequence getSummary() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, lastHour);
cal.set(Calendar.MINUTE, lastMinute);
DateFormat sdf = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT);
return sdf.format(cal.getTime());
}
}
add this for Summary:
#Override
public CharSequence getSummary() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, lastHour, lastMinute);
return DateFormat.getTimeFormat(getContext()).format(new Date(cal.getTimeInMillis()));
}
and add
setSummary(getSummary());
to end of onSetInitialValue and onDialogClosed.
I have modified CommonsWare answer to use JodaTime library:
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
import org.joda.time.LocalTime;
public class TimePreference extends DialogPreference {
private int lastHour;
private int lastMinute;
private TimePicker picker;
public TimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
#Override
protected View onCreateDialogView() {
picker = new TimePicker(getContext());
return(picker);
}
#Override
protected void onBindDialogView(#NonNull View v) {
super.onBindDialogView(v);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastHour = picker.getCurrentHour();
lastMinute = picker.getCurrentMinute();
LocalTime localTime = new LocalTime(lastHour, lastMinute);
String time = localTime.toString();
if (callChangeListener(time)) {
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
LocalTime time;
if (restoreValue) {
if (defaultValue == null) {
time = LocalTime.parse(getPersistedString("08:00:00.000"));
}
else {
time = LocalTime.parse(getPersistedString(defaultValue.toString()));
}
} else {
time = LocalTime.parse(defaultValue.toString());
}
lastHour = time.getHourOfDay();
lastMinute = time.getMinuteOfHour();
}
}
Also you will need to add a Custom preference like Sikora said.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="editTextPref_Key"
android:title="#string/editTextPref_title"/>
<com.example.myapp.TimePreference
android:key="timePrefA_Key"
android:title="#string/timePrefA_title"/>
<com.example.myapp.TimePreference
android:key="timePrefB_Key"
android:title="#string/timePrefB_title"/>
</PreferenceScreen>
With Android 6, "current hour" and "current minute" are deprecated. Use this to ensure Marshmallow compatibility:
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class TimePreference extends DialogPreference {
private int lastHour;
private int lastMinute;
private TimePicker picker;
public TimePreference(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
setPositiveButtonText(ctx.getString(android.R.string.ok));
setNegativeButtonText(ctx.getString(android.R.string.cancel));
}
#Override
protected View onCreateDialogView() {
picker = new TimePicker(getContext());
picker.setIs24HourView(true);
return picker;
}
#SuppressWarnings("deprecation")
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
} else {
picker.setHour(lastHour);
picker.setMinute(lastMinute);
}
}
#SuppressWarnings("deprecation")
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
lastHour = picker.getCurrentHour();
lastMinute = picker.getCurrentMinute();
} else {
lastHour = picker.getHour();
lastMinute = picker.getMinute();
}
String time = String.valueOf(lastHour) + ":" + String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time;
if (restoreValue) {
if (defaultValue == null) {
time = getPersistedString("00:00");
} else {
time = getPersistedString(defaultValue.toString());
}
} else {
time = defaultValue.toString();
}
lastHour = getHour(time);
lastMinute = getMinute(time);
}
public static int getHour(String time) {
String[] pieces = time.split(":");
return Integer.parseInt(pieces[0]);
}
public static int getMinute(String time) {
String[] pieces = time.split(":");
return Integer.parseInt(pieces[1]);
}
}
Like LEO87, I was seeing ClassCastException's. The problem was due to stale persisted data from a previous control of the same name. Possible solutions are to clear the app data, use a different name (key), or if you must use the same key name, catch the exception as follows:
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
long persistedValue;
try {
persistedValue = getPersistedLong(System.currentTimeMillis());
} catch (Exception e) {
//Stale persisted data may be the wrong type
persistedValue = System.currentTimeMillis();
}
calendar.setTimeInMillis(persistedValue);
} else if (defaultValue != null) {
calendar.setTimeInMillis(Long.parseLong((String) defaultValue));
} else {
//!restoreValue, defaultValue == null
calendar.setTimeInMillis(System.currentTimeMillis());
}
setSummary(getSummary());
}

Categories

Resources