Hey I'm trying to add an onSharedPreference Listener into n Fragment. It should regulate if a change is done (switch in the settings) the value of the NumberPicker inside the Fragment changes(0 or 1) too.
the problem with the listener: it only works the first 5-10 times then it doesnt get called anymore (i suppose)? -> no changes done on NumberPicker following the importants code of my fragment:
public class FragmentTwo extends Fragment {
private EditText mEnterWeight;
private NumberPicker mUnitPicker;
private TextView mConverted;
private int pick;
private String convertedWeightMessage;
private Double enteredWeight;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mEnterWeight = (EditText) view.findViewById(R.id.WCenterWeight);
mUnitPicker = (NumberPicker) view.findViewById(R.id.WCunitPicker);
mConverted = (TextView) view.findViewById(R.id.WCconverted);
initialiseUnitPicker();
//some stuff
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if(key.equals("SwitchMainUnit")) {
Boolean kg = prefs.getBoolean("SwitchMainUnit", true);
if(kg)
mUnitPicker.setValue(0);
else mUnitPicker.setValue(1);
}
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
return view;
}
The docs say that i need to change the onResume() and onPause() to:
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
But where do i need to add these? Got errors when i tried to add it in the Fragment.
Thanks for helping; didnt come to any solution myself.. :/