2016-06-01 52 views
0

我正在爲我的應用程序創建一個alerm類型通知,但面臨一個空指針error.From對話框片段,AlarmManager指示空。這是我的代碼。如何setAlarmManager在Android中的對話框片段

if(alermId>=0){ 
     Log.e("Alerm Id: ",""+alermId); 
      Intent alermReceiver = new Intent(getActivity(), AlermReceiver.class); 
      alermReceiver.setAction(DietInformation.ACTION_DIET); 
      alermReceiver.putExtra("title",titleView.getText()); 
      alermReceiver.putExtra("day",repeatView.getText()); 
      alermReceiver.putExtra("menu",menuView.getText()); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(),alermId,alermReceiver,0); 
      //ApplicationData.getAlarmManager().setRepeating(AlarmManager.RTC_WAKEUP,reminderTimeInMills,24*60*60*1000*7,pendingIntent); 
      //ApplicationMain.getAlarmManager().setRepeating(AlarmManager.RTC_WAKEUP,reminderTimeInMills,24*60*60*1000*7,pendingIntent); 
      //alarmManager = 
      AlarmClass.getAlarmManager().setRepeating(AlarmManager.RTC_WAKEUP,reminderTimeInMills,24*60*60*1000*7,pendingIntent); 
     } 

而且實例化Alarmanager我創建了一個內部類似如下

static class AlarmClass extends Application{ 
      public static AlarmManager alarmManager; 
      AlarmClass(){ 
       alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
      } 
      public static AlarmManager getAlarmManager() { 
       return alarmManager; 
      } 
     } 

但是應用程序顯示了一個空指針錯誤。像

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.AlarmManager.setRepeating(int, long, long, android.app.PendingIntent)' on a null object reference 
      at com.softmaker.gazi_opu.personalhealthcare.fragment.CreateDietFragment.setReminder(CreateDietFragment.java:406) 

任何人都可以建議我。如何爲setRepeating(....)實例化alarmMenager;

回答

2

嘗試在你的應用程序類

static class AlarmClass extends Application{ 
     public static AlarmManager alarmManager; 
     Context mContext; 
     AlarmClass(){ 
      mContext = this; 
      alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
     } 
     public static AlarmManager getAlarmManager() { 

      if(alarmManager==null){ 

      alarmManager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE); 

      } 
      return alarmManager; 
     } 
    } 
+0

我用這種方式試圖改變的代碼......但它沒有工作......另一件事,當我伸出應用,我要補充的onCreate()方法??? – opu