如何在SharedPreference和错误句柄中实现DatePicker对话框?

时间:2017-03-12 17:41:27

标签: java android date datepicker

当用户点击编辑文本时,我已经使用下面的代码创建了一个datepicker对话框,我已经厌倦了将日期保存为共享首选项中的字符串并将其作为字符串加载,但是当用户关闭并打开时应用程序再次收到有关nullObject引用的错误,我怎么能错误处理这个?

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()));
}

我已经厌倦了错误处理的代码,但它不起作用:

if (TextUtils.isEmpty(edittext.getText().toString())) {
                edittext.setError("Please select Date");
            }

保存我使用过代码的日期:

String currentDate = sdf.format(DCal.getTime());
SharedPreferences Dsave = getSharedPreferences(DateSave, this.MODE_PRIVATE);
        SharedPreferences.Editor editor = Dsave.edit();

        editor.putString("Date", currentDate);
editor.apply();

并加载我使用过:

 SharedPreferences Dload = getSharedPreferences(DateSave, Context.MODE_PRIVATE);
St_Date = Load.getString("Date", "");

edittext.setText(St_Date);

0 个答案:

没有答案