Android TimePickerDialog。当设置时间超过当前时间时,应用程序崩溃

时间:2015-07-13 11:15:07

标签: java android indexoutofboundsexception

当我尝试将时间设置为超过当前时间时,我的应用程序崩溃了。 请解决我的问题。 当前时间工作正常,但当我选择超过当前时间的时间时应用程序崩溃。 感谢

JavaFile:

package com.example.akshay.eventmanager;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.widget.Toast;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import android.app.DatePickerDialog.OnDateSetListener;


/**
 * Created by Akshay on 7/12/2015.
 */
public class Create extends Activity implements View.OnClickListener {

    Button select, create;
    EditText title, desc, time;
    TextView venueInfo;
    PlacePicker.IntentBuilder intentBuilder;
    private static final int PLACE_PICKER_REQUEST = 1;
    public LatLng gotLatLng;
    String placeName;
    String plName;
    String Addr;
    Double gotLat, gotLong;
    String LAT, LONG;
    DataBaseHelper myDB;
    public static final String LOG_TAG = "Create";

    String GotTime = " ";
    String GotDate = " ";

    DatePickerDialog datePicker;
    TimePickerDialog myTimePicker;
    SimpleDateFormat dateFormatter;
    SimpleDateFormat TimeFormatter;
    static boolean flag = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);
        dateFormatter = new SimpleDateFormat("EEEE dd" ,Locale.US);



        showDate();
        showTime();
        casting();
    }

    public void casting() {
        select = (Button) findViewById(R.id.bSelect);
        create = (Button) findViewById(R.id.bCreate);
        title = (EditText) findViewById(R.id.etTitle);
        desc = (EditText) findViewById(R.id.etDescription);
        time = (EditText) findViewById(R.id.etTime);
        venueInfo = (TextView) findViewById(R.id.tVVenue);
        time.setInputType(InputType.TYPE_NULL);

        select.setOnClickListener(this);
        create.setOnClickListener(this);
        time.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId())

        {
            case R.id.bSelect:
                try {
                    intentBuilder = new PlacePicker.IntentBuilder();

                    Intent intent = intentBuilder.build(Create.this);


                    startActivityForResult(intent, PLACE_PICKER_REQUEST);

                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();

                } catch (GooglePlayServicesNotAvailableException e) {
                    Toast.makeText(Create.this, "Google Play Services is not available.",
                            Toast.LENGTH_LONG)
                            .show();

                }
                break;


            case R.id.bCreate:
                String TITLE = title.getText().toString();
                String DESC = desc.getText().toString();
                String eventTime = time.getText().toString();
                String PLACE = venueInfo.getText().toString();
                myDB = new DataBaseHelper(this);
                Log.e(LOG_TAG, TITLE);
                Log.e(LOG_TAG, DESC);
                Log.e(LOG_TAG, PLACE);
                Log.e(LOG_TAG, LAT);
                Log.e(LOG_TAG, LONG);
                Log.e(LOG_TAG, Addr);
                Log.e(LOG_TAG, eventTime);
                int flag = myDB.InsertValues(TITLE, DESC, PLACE, LAT, LONG, Addr, eventTime);

                if (flag == 1) {
                    Toast.makeText(Create.this, "Sucess", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(Create.this, "Error Adding Records", Toast.LENGTH_LONG).show();
                }
                break;

            case R.id.etTime:
                myTimePicker.show();
                datePicker.show();
                break;

        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                Place place = PlacePicker.getPlace(data, this);
                gotLatLng = place.getLatLng();
                plName = (String) place.getName();
                Addr = (String) place.getAddress();
                gotLat = gotLatLng.latitude;
                gotLong = gotLatLng.longitude;
                LAT = String.valueOf(gotLat);
                LONG = String.valueOf(gotLong);
                placeName = String.format("Place: %s", place.getName());
                Toast.makeText(this, placeName, Toast.LENGTH_LONG).show();
                venueInfo.setText(plName);

            }
        }
    }

    public void showDate() {
        Calendar cal = Calendar.getInstance();
        datePicker = 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);
                GotDate = dateFormatter.format(newDate.getTime()).toString();


            }
        }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_WEEK));
flag =true;
    }

public void showTime() {
    if(flag == true) {

        Calendar calender = Calendar.getInstance();
        myTimePicker = new TimePickerDialog(this, new OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {


                Calendar newTime = Calendar.getInstance();

                newTime.set(hourOfDay, minute);
                GotTime = GotDate + " At " + String.valueOf(hourOfDay) + " :" + String.valueOf(minute + 1);
                time.setText(GotTime);
            }
        }, calender.get((Calendar.HOUR_OF_DAY)), calender.get(Calendar.MINUTE), true);
    }

    }
}

logcat的:

07-13 16:43:10.468      478-478/com.example.akshay.eventmanager E/Zygote﹕ MountEmulatedStorage()
07-13 16:43:10.468      478-478/com.example.akshay.eventmanager E/Zygote﹕ v2
07-13 16:43:10.468      478-478/com.example.akshay.eventmanager E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
07-13 16:43:29.338      478-478/com.example.akshay.eventmanager E/ViewRootImpl﹕ sendUserActionEvent() mView == null
07-13 16:43:31.088      478-478/com.example.akshay.eventmanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.akshay.eventmanager, PID: 478
    java.lang.ArrayIndexOutOfBoundsException: length=17; index=17
            at java.util.Calendar.set(Calendar.java:1122)
            at com.example.akshay.eventmanager.Create$2.onTimeSet(Create.java:196)
            at android.app.TimePickerDialog.onClick(TimePickerDialog.java:204)
            at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5972)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

1 个答案:

答案 0 :(得分:3)

使用showTime()方法在日历中设置时间,如下所示:

public void showTime() {
    if(flag == true) {

        Calendar calender = Calendar.getInstance();
        myTimePicker = new TimePickerDialog(this, new OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {


                Calendar newTime = Calendar.getInstance();

                //newTime.set(hourOfDay, minute); // remove this line

                //Add these two line
                newTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                newTime.set(Calendar.MINUTE, minute);

                GotTime = GotDate + " At " + String.valueOf(hourOfDay) + " :" + String.valueOf(minute + 1);
                time.setText(GotTime);
            }
        }, calender.get((Calendar.HOUR_OF_DAY)), calender.get(Calendar.MINUTE), true);
    }

    }

修改 要在上午/下午获得HourOdDay,你可以这样做:

String format = "hh:mm a"; // your own format
 SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
 String formated_time = sdf.format(newTime.getTime());  
 //formated_time would show you time like "hh:mm am/pm".