I want to update the NumberPicker using the value stored in Shared Preferences. This is all happening inside a fragment, there is also a button which calls the onValueChange()
method whenever the user clicks on it.
HomeFragment.java
import android.content.SharedPreferences;
import android.widget.NumberPicker;
public class HomeFragment extends Fragment {
NumberPicker numberPicker;
SharedPreferences sharedPref;
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
numberPicker = (NumberPicker) rootView.findViewById(R.id.np);
//Populate NumberPicker values from minimum and maximum value range
//Set the minimum value of NumberPicker
numberPicker.setMinValue(0);
//Specify the maximum value/number of NumberPicker
numberPicker.setMaxValue(239);
//Gets whether the selector wheel wraps when reaching the min/max value.
numberPicker.setWrapSelectorWheel(true);
//Set a value change listener for NumberPicker
final NumberPicker.OnValueChangeListener np_listener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal){
//Statement goes here...
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("someInteger", newVal);
editor.commit();
}
};
numberPicker.setOnValueChangedListener(np_listener);
b1 = (Button) rootView.findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int oldValue = numberPicker.getValue();
numberPicker.setValue(oldValue + 1);
np_listener.onValueChange(numberPicker, oldValue, oldValue + 1);
}
});
// Inflate the layout for this fragment
return rootView;
}
}
Whenever the NumberPicker value changes, I'm saving it in Preferences but where to retrieve the value? I know the code to retrieve:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int someInteger = sharedPref.getInt("someInteger", 0);
But where to put this code, inside onCreate()
or onCreateView()
? After the value is retrieved if it exists then how to call onValueChange()
so that all the statements inside that method gets executed?