为什么我会收到Unparsable Date错误?

时间:2012-08-15 16:05:12

标签: java android

我的代码告诉我我的约会时间不详,但我找不到它,有人可以帮助我吗?

public class TaskReminderActivity extends ListActivity 
{
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int START_PICKER_DIALOG = 1;
private static final int END_PICKER_DIALOG = 2;

//Date Time Format
private static final String DATE_FORMAT = "yyyy-MM-dd"; 
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";

private RemindersDbAdapter mDbHelper;
private EditText mName;
private Button mSend;
final Context context = this;
private String inputName;
private String inputPassword;
private Editable editName;
private Editable editPassword;
private Calendar mCalendar; 
private Calendar mCalendarEnd;
private Button mStartTimeButton;
private Button mEndTimeButton;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.reminder_list);
    StrictMode.ThreadPolicy policy = new     StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    mName = (EditText) findViewById(R.id.user_name);
    mSend = (Button) findViewById(R.id.send);
    mStartTimeButton = (Button) findViewById(R.id.main_startTime);
    mEndTimeButton = (Button) findViewById(R.id.main_endTime);

    mDbHelper = new RemindersDbAdapter(this);
    mCalendar = Calendar.getInstance();
    mCalendarEnd = Calendar.getInstance();

    //Code to increase size of buttons

    mDbHelper.open();
    fillData();
    registerForContextMenu(getListView());
    registerButtonListeners();

 }

@Override
protected Dialog onCreateDialog(int id) {
    switch(id) {
        case START_PICKER_DIALOG: 
            return startTimePicker();
        case END_PICKER_DIALOG: 
            return endTimePicker();
    }
    return super.onCreateDialog(id);
}

//Code for Picking start and end time
private TimePickerDialog startTimePicker() {

    TimePickerDialog timePicker = new TimePickerDialog(this, new   TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            mCalendar.set(Calendar.MINUTE, minute); 
            updateStartTimeButtonText(); 
        }
    }, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE),   true); 

    return timePicker; 
}

 private TimePickerDialog endTimePicker() {

TimePickerDialog timePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mCalendarEnd.set(Calendar.HOUR_OF_DAY, hourOfDay);
            mCalendarEnd.set(Calendar.MINUTE, minute); 
            updateEndTimeButtonText(); 
        }
    }, mCalendarEnd.get(Calendar.HOUR_OF_DAY), mCalendarEnd.get(Calendar.MINUTE), true); 

return timePicker; 
}

private void registerButtonListeners() 
{
    //Time Listeners
    mStartTimeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showDialog(START_PICKER_DIALOG); 
        }
    });

    mEndTimeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showDialog(END_PICKER_DIALOG); 
        }
    });

    // add button listener
            mSend.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    // get prompts.xml view
                    LayoutInflater li = LayoutInflater.from(context);
                    View promptsView = li.inflate(R.layout.prompts,     null);

                    AlertDialog.Builder alertDialogBuilder = new     AlertDialog.Builder(
                            context);

                    // set prompts.xml to alertdialog builder
                    alertDialogBuilder.setView(promptsView);

                    final EditText userInput = (EditText) promptsView
                                .findViewById(R.id.usernameTextDialogUserInput);

                    final EditText passwordInput = (EditText) promptsView
                            .findViewById(R.id.passwordTextDialogUserInput);

                    // set dialog message
                    alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                          new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                            // get user input and set it to result
                            // edit text
                                FileWrite();

                                editName = userInput.getText();
                                editPassword =   passwordInput.getText();

                                inputName = editName.toString();
                                inputPassword = editPassword.toString();

                                Mailing(inputName, inputPassword);
                            }
                          })
                        .setNegativeButton("Cancel",
                          new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                            dialog.cancel();
                            }
                          });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();

                }
            });

            updateStartTimeButtonText();
            updateEndTimeButtonText();
}

//Code for updating time buttons
private void updateStartTimeButtonText() {
    // Set the time button text based upon the value from the database
    SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT); 
    String timeForButton = timeFormat.format(mCalendar.getTime()); 

    mStartTimeButton.setText(timeForButton);
}

private void updateEndTimeButtonText() {
    // Set the time button text based upon the value from the database
    SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT); 
    String timeForButton = timeFormat.format(mCalendarEnd.getTime());

    mEndTimeButton.setText(timeForButton);
}

private void fillData() 
{
    Cursor remindersCursor = mDbHelper.fetchAllReminders();
    startManagingCursor(remindersCursor);


    // Create an array to specify the fields we want to display in the list (only   TITLE)
    String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};

    // and an array of the fields we want to bind those fields to (in this case just text1)
    int[] to = new int[]{R.id.text1};

    // Now create a simple cursor adapter and set it to display
    SimpleCursorAdapter reminders = 
            new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
    setListAdapter(reminders);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater mi = getMenuInflater();
    mi.inflate(R.menu.list_menu, menu); 
    return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch(item.getItemId()) {
    case R.id.menu_insert: 
        createReminder();
        return true; 
    case R.id.menu_settings: 
        Intent i = new Intent(this, TaskPreferences.class); 
        startActivity(i); 
        return true;
    }

    return super.onMenuItemSelected(featureId, item);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater mi = getMenuInflater(); 
    mi.inflate(R.menu.list_menu_item_longpress, menu); 
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.menu_delete:
            AdapterContextMenuInfo info = (AdapterContextMenuInfo)   item.getMenuInfo();
            mDbHelper.deleteReminder(info.id);
            fillData();
            return true;
    }
    return super.onContextItemSelected(item);
}

private void createReminder() {
    Intent i = new Intent(this, ReminderEditActivity.class);
    startActivityForResult(i, ACTIVITY_CREATE);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Intent i = new Intent(this, ReminderEditActivity.class);
    i.putExtra(RemindersDbAdapter.KEY_ROWID, id);
    startActivityForResult(i, ACTIVITY_EDIT); 
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    fillData();
}

  //Prepares the email to be sent
public void Mailing(String inputName, String inputPassword)
{
    Mail m = new Mail(inputName, inputPassword); 

    String[] toArr = {"brittany@schoellersinc.com"}; 
    m.setTo(toArr); 
    m.setFrom(inputName); 
    m.setSubject("Daily Time Card"); 
    m.setBody(""); 

    try { 
      m.addAttachment(Environment.getExternalStorageDirectory().toString() + "/test"); 

      if(m.send()) 
      { 
        Toast.makeText(TaskReminderActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
      }

    } catch(Exception e) { 
      Toast.makeText(TaskReminderActivity.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
      Toast.makeText(TaskReminderActivity.this, "Value of User Name is " + inputName, Toast.LENGTH_LONG).show();
      Toast.makeText(TaskReminderActivity.this, "Value of Password is " + inputPassword, Toast.LENGTH_LONG).show();
      Toast.makeText(TaskReminderActivity.this, "Value of Attachment is " +   Environment.getExternalStorageDirectory().toString() + "/test.txt", Toast.LENGTH_LONG).show();
      Log.e("MailApp", "Could not send email", e); 
    } 
}

public void FileWrite()
{
    Cursor remindersCursor = mDbHelper.fetchAllReminders();
    startManagingCursor(remindersCursor);

    try 
    { // catches IOException below
        String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
        final String TESTSTRING = new String(RemindersDbAdapter.KEY_TITLE + "   ");
        File sdCard = Environment.getExternalStorageDirectory();
        File myFile = new File(sdCard, "test");
        FileWriter writer = new FileWriter(myFile);
        writer.append(showEvents(remindersCursor));
        writer.flush();
        writer.close();


        Toast.makeText(TaskReminderActivity.this, "Program Successfully went through FileWrite!", Toast.LENGTH_LONG).show();
    } catch(Exception e) 
    { 
          Toast.makeText(TaskReminderActivity.this, "Had Problems with file!", Toast.LENGTH_LONG).show();
          Log.e("FileWrite", "Had Problems with file!", e); 
    }
}

private StringBuilder showEvents(Cursor cursor) throws ParseException 
{

    Editable EditName = mName.getText();
    String Name = EditName.toString();
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
    SimpleDateFormat TimeFormat = new SimpleDateFormat(TIME_FORMAT);
    SimpleDateFormat DateFormat = new SimpleDateFormat(DATE_FORMAT);

    Date startTimer;
    Date endTimer;
    Date timeConverter;
    long totalBillable = 0;
    long hours;
    long minutes;
    String thisBill;
    String dateTimeString;
    String startString;
    String endString;
    boolean Lunch = false;

    StringBuilder ret = new StringBuilder(Name + "'s Time Card:\n\n");

    dateTimeString = DateFormat.format(mCalendar.getTime());
    startString = TimeFormat.format(mCalendar.getTime());
    endString = TimeFormat.format(mCalendarEnd.getTime());

    Toast.makeText(TaskReminderActivity.this, "startString = " + startString, Toast.LENGTH_LONG).show();
    Toast.makeText(TaskReminderActivity.this, "endString = " + endString, Toast.LENGTH_LONG).show();

    ret.append("Today's Date: " + dateTimeString + "\n");
    ret.append("Start Time: " + startString + "\n");
    ret.append("Finish Time: " + endString + "\n\n");

    cursor.moveToPosition(-1);
    //loop for lunch
    while (cursor.moveToNext())
    {


        if(cursor.getString(1).equals("lunch") ||   cursor.getString(1).equals("Lunch") || cursor.getString(1).equals("LUNCH"))
        {
            Lunch = true;
        }
        else
        {
            Lunch = false;
        }

    }

    cursor.moveToPosition(-1);

    //Find the payable hours.
    startTimer = mCalendar.getTime();
    endTimer = mCalendarEnd.getTime();  

    //Condition to see what payable hours is with lunch break
    if(Lunch == false)
    {
        totalBillable += endTimer.getTime() - startTimer.getTime();

        totalBillable = (totalBillable/1000);
        hours = (totalBillable/3600);
        minutes = (totalBillable/60);
        totalBillable = totalBillable - (hours * 3600);
        minutes = totalBillable / 60;
        thisBill = ("Total Payable Hours: " + hours + " hours "  + minutes + " minutes");
        ret.append(thisBill + "\n");
    }
    else
    {
        totalBillable += endTimer.getTime() - startTimer.getTime();

        totalBillable = ((totalBillable-1800000)/1000);
        hours = (totalBillable/3600);
        minutes = (totalBillable/60);
        totalBillable = totalBillable - (hours * 3600);
        minutes = totalBillable / 60;
        thisBill = ("Total Payable Hours: " + hours + " hours "  + minutes + " minutes");
        ret.append(thisBill + "\n");
    }

    cursor.moveToPosition(-1);

    //Loop for calculating total billable
    while (cursor.moveToNext()) 
    {   
        if(cursor.getString(1).equals("lunch") ||    cursor.getString(1).equals("Lunch") || cursor.getString(1).equals("LUNCH") || cursor.getString(1).equals("shop") || cursor.getString(1).equals("SHOP") || cursor.getString(1).equals("Shop"))
        {

        }
        else
        {
            try
            {
                String dateString = cursor.getString(6); 
                startTimer = TimeFormat.parse(dateString); 

                //Code for End Time
                String endDateString = cursor.getString(7); 
                endTimer = TimeFormat.parse(endDateString);

                totalBillable += endTimer.getTime() - startTimer.getTime();           

            }catch (ParseException e) {
                Log.e("ReminderEditActivity", e.getMessage(), e);
            }   
        }


    }

    totalBillable = (totalBillable/1000);
    hours = (totalBillable/3600);
    minutes = (totalBillable/60);
    totalBillable = totalBillable - (hours * 3600);
    minutes = totalBillable / 60;
    thisBill = ("Total Billable Hours: " + hours + " hours "  + minutes + " minutes");
    ret.append(thisBill + "\n\n");

    //Enters the main entries into the file
    cursor.moveToPosition(-1);
    ret.append("Customer Name   " + "Customer Number    " + "Job Number " +     "Preparation Time   " + "Travel Time    " + "Start Time " + "End Time   " + "Billed Time    " + "Job Completed  \n");
    while (cursor.moveToNext()) 
    {

      String title = cursor.getString(1);
      String customer = cursor.getString(2);
      String job = cursor.getString(3);
      String prepare = cursor.getString(4);
      String travel = cursor.getString(5);
      String dateTime = cursor.getString(6);
      String endTime = cursor.getString(7);
      String billed = cursor.getString(8);
      String completed = cursor.getString(9);

      //Loop to make file more readable
      if(completed.equals("1"))
      {
          completed = "Yes";
      }
      else
      {
          completed = "No";
      }

      ret.append(title + "  " + customer + "    " + job + " " + prepare + " " +       travel + "    " + dateTime + "    " + endTime + " " + billed + "  " + completed + "       " + "\n");
    }
    return ret;
  }
 }`

日志:

08-15 15:41:37.070: E/ReminderEditActivity(582): Unparseable date: "2012-07-02 14:17:25" (at offset 4)
08-15 15:41:37.070: E/ReminderEditActivity(582): java.text.ParseException: Unparseable date: "2012-07-02 14:17:25" (at offset 4)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at java.text.DateFormat.parse(DateFormat.java:626)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at com.dummies.android.TaskReminder.TaskReminderActivity.showEvents(TaskReminderActivity.java:464)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at com.dummies.android.TaskReminder.TaskReminderActivity.FileWrite(TaskReminderActivity.java:354)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at com.dummies.android.TaskReminder.TaskReminderActivity$5$1.onClick(TaskReminderActivity.java:186)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at android.os.Looper.loop(Looper.java:137)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at android.app.ActivityThread.main(ActivityThread.java:4424)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at java.lang.reflect.Method.invokeNative(Native Method)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at java.lang.reflect.Method.invoke(Method.java:511)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-15 15:41:37.070: E/ReminderEditActivity(582):    at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

看看这段代码......

try
{
    String dateString = cursor.getString(6); 
    startTimer = TimeFormat.parse(dateString); 

    //Code for End Time
    String endDateString = cursor.getString(7); 
    endTimer = TimeFormat.parse(endDateString);

    totalBillable += endTimer.getTime() - startTimer.getTime();           

}catch (ParseException e) {
    Log.e("ReminderEditActivity", e.getMessage(), e);
}

很难确定,因为您的问题中发布的内容太多了,但您的意思是dateTimeFormat而不是TimeFormat吗?

答案 1 :(得分:0)

倾销“只有519行代码”,甚至没有指出哪一行代码是提出异常的代码,这无助于我们回答你的问题。

此外,Java命名约定不会使用大写字母命名数据成员和局部变量。 TimeFormat看起来像是一个类名,让像我们这样的人很难理解“只有519行代码”。

话虽如此,TimeFormat基于kk:mm,您的数据(2012-07-02 14:17:25)不是那种格式。您不应该使用TimeFormat,或者数据库中的数据是错误的。