开发者

Simple Date Formatter parse function error

I am getting an error when I use SimpleDateFormatter.parse() function. I am making user enter the date and time through DatePicker and TimePicker respectively and I am collecting the information from both the pickers and trying to create a Date object do that I could compare it to another date object (System Date).

But when I am trying to parse the date to form a date format I am getting the error.

Simple Date Formatter parse function error

The chunk of code causing the error is

 btn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
         int day =  dpicker.getDayOfMonth();
         int month = dpicker.getMonth() + 1;

       开发者_运维问答  if (month < 10)
         {
             monthS = "0" + month;
         }
         else
         {
             monthS = String.valueOf(month);
         }
         int year = dpicker.getYear();

         int minutes = tpicker.getCurrentMinute();
         int hours = tpicker.getCurrentHour();
         if (hours < 10)
         {
             hoursS = "0" + hours;
         }
         else
         {
             hoursS = String.valueOf(hours);
         }


          date = year + "-" + monthS + "-" + day + " " + hoursS + ":" +  minutes  ; 

         tview.setText("Date and Time are" + date) ;


        }
    });

   SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd hh:MM");

   try {
     newDate = sdf.parse(date);

} catch (java.text.ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
tview2.setText(newDate.toString());

I would appreciate any help on this error.

Thanks, Sid


You parse date outside of onClick listener, so, maybe, at that time variable date is not initialized. I think you should move try/catch cycle inside listener.


The problem is that date is null. The code inside your onClickListener will not execute until the button is pressed.


This is not the sdf object that is not initialized, this is probably the data String that is still null (although we can't be sure until we see the code before it). You try to parse date, but from what you posted, you only modify/put value to it in the OnClickListener which is not called until the click.

So what you basically do is:

  1. declare string date.
  2. set onclicklistener.
  3. use the string date before you initialize it.

Fix it by setting a default value to date or put the parsing in the listener as well (whatever answers the correct logic you need)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜