0

我正在开发一个在指定时间发送 SMS 的 Android 应用程序。但是,当我检查是否在日期上进行验证以检查其是否为未来日期时,应用程序会停止。当我在评论中激活代码时会弹出错误。

package com.example.sked;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

import android.app.Activity;

import android.app.AlarmManager;

import android.app.AlertDialog;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.DatePicker;

import android.widget.EditText;

import android.widget.TimePicker;

import android.widget.Toast;



public class ScheduleActivity extends Activity
{
    private PendingIntent pendingIntent;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_schedule);
        super.onCreate(savedInstanceState);

        Calendar cal=Calendar.getInstance();

        final int year_set=cal.get(Calendar.YEAR);
        final int month_set=cal.get(Calendar.MONTH);
        final int day_set=cal.get(Calendar.DAY_OF_MONTH);

        final int hr_set=cal.get(Calendar.HOUR);
        final int min_set=cal.get(Calendar.MINUTE);

        final   DatePicker dp_c = (DatePicker) findViewById(R.id.datePicker1);
        final   TimePicker tp_c = (TimePicker) findViewById(R.id.timePicker1);

        dp_c.updateDate(year_set, month_set, day_set); //Setting current date in date picker //

        tp_c.setCurrentHour(hr_set);  //Setting current time in time picker //
        tp_c.setCurrentMinute(min_set);


        //For Scheduling a message//
        final Button view = (Button) findViewById(R.id.set_message);
        {
        view.setOnClickListener(new View.OnClickListener()
        {

        @Override
        public void onClick(View v)
        {


            // Processing the input values from the user//  
            EditText text = (EditText)findViewById(R.id.reci_number);
            final String phno= text .getText().toString();

            EditText text1 = (EditText)findViewById(R.id.message);
            final String msg= text1.getText().toString();

            if(phno.length()==10)//Checking length of the mobile number//
            {
            if(msg.length()<=160 && msg.length()>0) //Checking length of the message//
            {


            DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);//Getting selected date values// 
            int day = dp.getDayOfMonth();
            int month = dp.getMonth() + 1;
            int year = dp.getYear();

            TimePicker tp=(TimePicker) findViewById(R.id.timePicker1);//Getting selected time values//
            int hours= tp.getCurrentHour();
            int minutes= tp.getCurrentMinute();


            Calendar cal=Calendar.getInstance();//Getting Current date values//

            final int year_curr=cal.get(Calendar.YEAR);
            final int month_curr=cal.get(Calendar.MONTH);
            int day_curr=cal.get(Calendar.DAY_OF_MONTH);

            final int hr_curr=cal.get(Calendar.HOUR);//Getting Current time values//
            final int min_curr=cal.get(Calendar.MINUTE);

            //String curr_values = year_curr + "-" + month_curr + "-" +day_curr+ "-"+ hr_curr + "-" +min_curr;

            //String sel_values = year + "-" + month + "-" +day+ "-"+ hours + "-" +minutes;

            //DateFormat df = new SimpleDateFormat("YY-MM-HH-mm-ss", Locale.ENGLISH);

            //try {
                //if (df.parse(sel_values).after(df.parse(curr_values)))//Checking if its the future date//
                //{



                    Intent myIntent = new Intent(ScheduleActivity.this, MyAlarmService.class);

                    Bundle bundle = new Bundle();
                    bundle.putCharSequence("extraSmsNumber", phno);
                    bundle.putCharSequence("extraSmsText", msg);
                    myIntent.putExtras(bundle);

                    pendingIntent = PendingIntent.getService(ScheduleActivity.this, 0, myIntent, 0);

                int year_act=year-year_curr;
                int year_act_indays=year_act*365;
                long year_act_mil=TimeUnit.MILLISECONDS.convert(year_act_indays, TimeUnit.DAYS);

                int mon_act=month-month_curr;
                int mon_act_indays=mon_act*30;
                long mon_act_mil=TimeUnit.MILLISECONDS.convert(mon_act_indays, TimeUnit.DAYS);

                int day_act=day-day_curr;
                long day_act_mil=TimeUnit.MILLISECONDS.convert(day_act, TimeUnit.DAYS);

                int hr_act=hours-hr_curr;
                long hr_act_mil=TimeUnit.MILLISECONDS.convert(hr_act, TimeUnit.HOURS);

                int min_act=minutes-min_curr;
                long min_act_mil=TimeUnit.MILLISECONDS.convert(min_act, TimeUnit.MINUTES);


                long elapsedtimer_act= year_act_mil+mon_act_mil+day_act_mil+hr_act_mil+min_act_mil;

                AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

                alarmManager.set(AlarmManager.RTC_WAKEUP,elapsedtimer_act, pendingIntent);

                final AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(ScheduleActivity.this, 0);

                //set  the dialog  
                dlgAlert.setMessage("Message successfully scheduled at the specified time & date");
                dlgAlert.setTitle("Success");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();




                //}
                //else 
                //{}
            //} catch (ParseException e) {
                // TODO Auto-generated catch block
                //Toast.makeText(getBaseContext(),
                //"Please check the entered date...And enter future time. ",Toast.LENGTH_SHORT).show();
            //  e.printStackTrace();
            //}
            }  

            else
            {

                Toast.makeText(getBaseContext(),
                "Message too long or too short .... cannot send ... :( ",Toast.LENGTH_SHORT).show();
            }
            }
            else
            {

                Toast.makeText(getBaseContext(), 
                    "Check the number Entered",Toast.LENGTH_SHORT).show();
            }
            }


        }

        );



        }



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.schedule, menu);
        return true;
    }

}    

日志输出:

09-12 11:53:11.259: D/InputEventConsistencyVerifier(779): KeyEvent: ACTION_UP but key was not down.
09-12 11:53:11.259: D/InputEventConsistencyVerifier(779):   in android.widget.EditText{41764990 VFED..CL .F....I. 16,89-464,289 #7f08000d app:id/message}
09-12 11:53:11.259: D/InputEventConsistencyVerifier(779):   0: sent at 148929000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=148929, downTime=148829, deviceId=0, source=0x101 }
09-12 11:53:12.978: D/dalvikvm(779): GC_FOR_ALLOC freed 225K, 9% free 3234K/3520K, paused 33ms, total 39ms
09-12 11:53:21.018: D/AndroidRuntime(779): Shutting down VM
09-12 11:53:21.018: W/dalvikvm(779): threadid=1: thread exiting with uncaught exception (group=0x41465700)
09-12 11:53:21.038: E/AndroidRuntime(779): FATAL EXCEPTION: main
09-12 11:53:21.038: E/AndroidRuntime(779): java.lang.IllegalArgumentException: Unknown pattern character 'Y'
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.text.SimpleDateFormat.validateFormat(SimpleDateFormat.java:264)
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:312)
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:365)
09-12 11:53:21.038: E/AndroidRuntime(779):  at com.example.sked.ScheduleActivity$1.onClick(ScheduleActivity.java:102)
09-12 11:53:21.038: E/AndroidRuntime(779):  at android.view.View.performClick(View.java:4240)
09-12 11:53:21.038: E/AndroidRuntime(779):  at android.view.View$PerformClick.run(View.java:17721)
09-12 11:53:21.038: E/AndroidRuntime(779):  at android.os.Handler.handleCallback(Handler.java:730)
09-12 11:53:21.038: E/AndroidRuntime(779):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-12 11:53:21.038: E/AndroidRuntime(779):  at android.os.Looper.loop(Looper.java:137)
09-12 11:53:21.038: E/AndroidRuntime(779):  at android.app.ActivityThread.main(ActivityThread.java:5103)
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.lang.reflect.Method.invokeNative(Native Method)
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.lang.reflect.Method.invoke(Method.java:525)
09-12 11:53:21.038: E/AndroidRuntime(779):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-12 11:53:21.038: E/AndroidRuntime(779):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-12 11:53:21.038: E/AndroidRuntime(779):  at dalvik.system.NativeStart.main(Native Method)
09-12 11:53:24.928: W/ResourceType(827): Skipping entry 0x106000b in package table 0 because it is not complex!
09-12 11:53:25.608: D/dalvikvm(827): GC_FOR_ALLOC freed 78K, 5% free 2941K/3080K, paused 55ms, total 66ms
09-12 11:53:25.848: D/gralloc_goldfish(827): Emulator without GPU emulation detected.
09-12 11:53:26.348: I/Choreographer(827): Skipped 48 frames!  The application may be doing too much work on its main thread.
4

2 回答 2

1
java.lang.IllegalArgumentException: Unknown pattern character 'Y'
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.text.SimpleDateFormat.validateFormat(SimpleDateFormat.java:264)
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:312)
09-12 11:53:21.038: E/AndroidRuntime(779):  at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:365)
09-12 11:53:21.038: E/AndroidRuntime(779):  at com.example.sked.ScheduleActivity$1.onClick(ScheduleActivity.java:102)

年份的模式字符是小写的y。所以,改变这个

DateFormat df = new SimpleDateFormat("YY-MM-HH-mm-ss", Locale.ENGLISH);

类似于

DateFormat df = new SimpleDateFormat("yyyy-MM-HH-mm-ss", Locale.ENGLISH);

(请注意,您似乎也错过了那里的每一天)

进一步阅读:http: //developer.android.com/reference/java/text/SimpleDateFormat.html

于 2013-09-12T12:03:43.533 回答
0

最简单的解决方案是检查当前日期和时间值所选日期和时间值之间的差异。如果差异大于0,则为未来时间。这是最简单的解决方案,因为 datepicker 和 timepicker 的返回类型值是int 。它也适用于日期选择器对话框时间选择器对话框

于 2013-09-14T09:11:35.147 回答