运行Android服务时运行Java Null指针异常

时间:2014-03-05 17:57:22

标签: java android

服务在MainActivity的onCreate中设置的每日时间运行,然后重置24小时。

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 17);
    calendar.set(Calendar.MINUTE, 32);
    calendar.set(Calendar.SECOND, 00);


    Intent intent = new Intent(this, MyReceiver.class);
    PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);


    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pintent);

我的服务类看起来像这样:

public int onStartCommand(Intent intent, int flags, int startId) {
   Toast.makeText(getApplicationContext(), "ITS TIME!" ,Toast.LENGTH_SHORT).show();
   myDb.open();
   try{
        Document doc = Jsoup.connect("http://www.sportinglife.com/racing/abc-guide/tomorrow").get();

        Elements tableElements = doc.select("table");
        Elements tableRowElements = tableElements.select(":not(thead) tr");
        for (int i = 1; i < tableRowElements.size(); i++) {
            Element row = tableRowElements.get(i);
            Elements rowItems = row.select("td");

            for (int j = 0; j < 3; j++) {
                if (j==0){
                       title = rowItems.get(j).text();
                }
                if (j==1){
                       title1 = rowItems.get(j).text();
                }
                if (j==2){
                       title2 = rowItems.get(j).text();
                }

            }
            long newId = myDb.insertRow(title, title1, title2);                 
        }
    }
    catch(Exception e) {
        e.printStackTrace();                
    }myDb.close();
    return startId;
 }

当时机到来并且服务完成时,我在日志中收到以下错误:

    03-05 17:54:00.636: E/AndroidRuntime(29057): FATAL EXCEPTION: main
    03-05 17:54:00.636: E/AndroidRuntime(29057): java.lang.RuntimeException: Unable to start service ca.demo.databasedemo.MyReceiver@429be418 with Intent { flg=0x4 cmp=ca.demo.databasedemo/.MyReceiver (has extras) }: java.lang.NullPointerException
    03-05 17:54:00.636: E/AndroidRuntime(29057):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2858)
    03-05 17:54:00.636: E/AndroidRuntime(29057):    at android.app.ActivityThread.access$2000(ActivityThread.java:165)
    03-05 17:54:00.636: E/AndroidRuntime(29057):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1429)

编辑: 我的清单文件还包含

    <service android:name=".MyReceiver"></service>

0 个答案:

没有答案