在 Android 应用程序中设置日期时出现 NullPointerException

NullPointerException when setting Date in Android app

我正在关注此 tutorial 以实现点击编辑文本时的日期和时间。

public class LoadActivity extends AppCompatActivity {

 @SuppressLint("StaticFieldLeak")
 static EditText DateEdit;
  
  @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_load);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
     
     EditText startTimeEditText = (EditText) findViewById(R.id.start_time);   

    startTimeEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showTruitonTimePickerDialog(v);
            showTruitonDatePickerDialog(v);
        }
    });

   


}  // end onCreate



   public void showTruitonDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}

public static class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(requireActivity(), this, year, month, day);
    }

  
}

    @SuppressLint("SetTextI18n")
    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        DateEdit.setText(day + ":" + (month + 1) + ":" + year);
    }


}// end main class

我可以在我的 app 中看到日期片段,但是当我按下 ok 按钮时,应用程序崩溃并且出现错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference at com.thumbsol.accuratemobileassetsmanagament.LoadActivity$DatePickerFragment.onDateSet(LoadActivity.java:300) at android.app.DatePickerDialog.onClick(DatePickerDialog.java:134)

行号300DateEdit.setText(day + ":" + (month + 1) + ":" + year);

我怎样才能摆脱这个错误?任何帮助将不胜感激。

那是因为您没有在代码中的任何位置设置 DateEdit 的值。

提示:尽量不要将视图用​​作静态视图。这可能会导致泄漏。

你只需要定义static EditText DateEdit,还需要通过findViewById获取。 例如:

DateEdit = (EditText) findViewById(R.id.date_edit);