I have used the code below to create a datepicker dialog when the user clicks on the edit text, i have tired to save the date as a string within shared preference and load it as a string, however when the user closes and opens the application again i receive an error regarding nullObject reference, how can i error handle this?
Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
edittext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(classname.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
private void updateLabel() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
edittext.setText(sdf.format(myCalendar.getTime()));
}
i have tired the code to error handle but it does not work:
if (TextUtils.isEmpty(edittext.getText().toString())) {
edittext.setError("Please select Date");
}
to save the date i have used the code:
String currentDate = sdf.format(DCal.getTime());
SharedPreferences Dsave = getSharedPreferences(DateSave, this.MODE_PRIVATE);
SharedPreferences.Editor editor = Dsave.edit();
editor.putString("Date", currentDate);
editor.apply();
and to load i have used:
SharedPreferences Dload = getSharedPreferences(DateSave, Context.MODE_PRIVATE);
St_Date = Load.getString("Date", "");
edittext.setText(St_Date);