Ошибка в Android Редактировать текст Onclick Datepickerdialog в леденце

1

Я использую datepickerdialog. он работает правильно на kitkat, но когда я запускаю приложение на леденец, и когда я нажимаю на редактирование текста, он открывает окно datepickerdialog, но когда я выбираю дату, он, к сожалению, останавливает ошибку. Ниже приведен код для datepicker на edittext.

private void setDateTimeField() {
                     fromLabel.setOnClickListener(this);
                     toLabel.setOnClickListener(this);



                     final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");  //yyyy/MM/dd HH:mm:ss
                    final Date date = new Date();
                    final String u = dateFormat.format(date);


                     Calendar newCalendar = Calendar.getInstance();
                     fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {

                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                             Calendar newDate = Calendar.getInstance();

                             newDate.set(year, monthOfYear, dayOfMonth);
                             from1 = dateFormatter.format(newDate.getTime());
                             diff1 = newDate.getTimeInMillis();
                             long d = date.getTime();


                             if((newDate.getTime()).equals(date)||(newDate.getTime()).after(date)){
                                 long d1 = (diff1 / (24 * 60 * 60 * 1000) - d / (24 * 60 * 60 * 1000)) + 1;
                                   if(d1>30){ 
                                         total.setVisibility(View.VISIBLE);
                                         total.setText("Booking not allowed as the Date given is outside Advance Booking Period");
                                         avail.setVisibility(View.GONE);

                                     }
                                   else{
                                         total.setVisibility(View.GONE);
                                         fromLabel.setText(from1);
                                         toLabel.setText(null);
                                         to=null;
                                         avail.setVisibility(View.GONE);
                                         from=fromLabel.getText().toString();
                                   }
                             }
                             else{
                                 total.setVisibility(View.VISIBLE);
                                 total.setText("Choose date after or equals to current date");
                                 fromLabel.setText("");
                                 toLabel.setText(null);     
                                 from=null;     
                                 to=null;
                             }


                         }

                     },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));



                     fromDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Done), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                           if (which == DialogInterface.BUTTON_POSITIVE) {
                               dialog.cancel();
                               if(type.equals("According to time"))
                               {

                                  int cnt=-1;
                                 if(from1.equals(u)){
                                     cnt = 1;
                                     loadTimeSpinnerDataATT(text,from,cnt);
                                  }
                                  else if(total.getText()=="Choose date after or equals to current date")
                                  {

                                  }
                                  else if(total.getText()=="Booking not allowed as the Date given is outside Advance Booking Period")
                                  {

                                  }
                                 else
                                 {cnt = 0;

                                  loadTimeSpinnerDataATT(text,from,cnt);
                                 }

                               }
                           }
                        }
                      });

                 }


                 public void onClick(View view) {
                     if(view == fromLabel) {
                         fromDatePickerDialog.show();
                     } else if(view == toLabel) {
                         toDatePickerDialog.show();

                     }        
                 }


                 public void onClose(DialogInterface dialogInterface)
                 {

                 }
          }
  • 0
    Когда вы получите, к сожалению, Stop Error, то вы получите исключение. Проверьте это в Logcat и выясните причину или вставьте сюда трассировку стека исключений, чтобы мы могли помочь.
Теги:
datepickerdialog

1 ответ

0
Лучший ответ

Попробуйте, может вам помочь,

Ошибка выбора даты.

Ссылка для выбора даты

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

    private int year;
    private int month;
    private int day;
    static final int DATE_PICKER_ID = 1111;

    // for date picker
     EditText m3_DateDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

         setContentView(R.layout.activity_main);

        m3_DateDisplay = (EditText) findViewById(R.id.datepick);

        // Get current date by calender

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);




        // Show selected date
        StringBuilder dateValue1 = new StringBuilder().append(day).append("-")
                .append(month + 1).append("-").append(year).append(" ");

        // for Converting Correct Date format Save into Database
        SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
        String abs1 = dateValue1.toString();
        Date testDate1 = null;
        try {
            testDate1 = sdf123.parse(abs1);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
        String DateFormat = formatter1.format(testDate1);

        m3_DateDisplay.setText(DateFormat);

        m3_DateDisplay.setFocusable(false);
        m3_DateDisplay.setInputType(InputType.TYPE_NULL);
        m3_DateDisplay.setOnClickListener(new View.OnClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                showDialog(DATE_PICKER_ID);
            }
        });

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_PICKER_ID:

            // open datepicker dialog.
            // set date picker for current date
            // add pickerListener listner to date picker
            // return new DatePickerDialog(this, pickerListener, year, month,
            // day);

            // ///Only Show till Date Not More than That.
            DatePickerDialog dialog = new DatePickerDialog(this,
                    pickerListener, year, month, day);
            dialog.getDatePicker().setMaxDate(new Date().getTime());
            return dialog;
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {

            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            // Show selected date
            StringBuilder dateValue = new StringBuilder().append(day)
                    .append("-").append(month + 1).append("-").append(year)
                    .append(" ");

            // for Converting Correct Date format Save into Database
            SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
            String abs1 = dateValue.toString();
            Date testDate1 = null;
            try {
                testDate1 = sdf123.parse(abs1);
            } catch (ParseException e) {

                e.printStackTrace();
            }
            SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
            String DateFormat = formatter1.format(testDate1);

            m3_DateDisplay.setText(DateFormat);

        }
    };
}

изменить минимум api-11 в манифесте

  • 0
    это будет работать на всех API Android?
  • 0
    проверь уже этот код работал в lolipop
Показать ещё 10 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню