Search code examples
androidpush-notificationandroid-notificationsandroid-calendar

Null Pointer Exception after setting HARD CODE values to Calendar Instance


I'm working on android push notification with Android services.

It's works like a charm when I select the date/month/year from the datepicker (see the code below) . But when I trying to set the calender instance with hard code values it's give me a NULL POINTER EXCEPTION.

How I tried:

I tried two method for this but from both I'm getting an exception.

1. method

    Calendar c = Calendar.getInstance();
    c.clear();
    int year = 2014;
    int month = 3;
    int day = 21;
    c.set(year, month, day); 

2. Method

    Calendar c = Calendar.getInstance();
    Calendar dt = Calendar.getInstance();
    dt.clear();
    dt.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));

MainActivity:

private ScheduleClient scheduleClient;

private SharedPreferences prefs; 
private String prefName = "userPrefs";
private static final String TITLE_KEY = "title"; 

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

    // Create a new service client and bind our activity to this service
    scheduleClient = new ScheduleClient(this);
    scheduleClient.doBindService();


    t1 = (TextView) findViewById(R.id.txt);
    nofitication();
}

private void nofitication(){

    Calendar c = Calendar.getInstance();
    c.clear();
    int year = 2014;
    int month = 3;
    int day = 21;
    c.set(year, month, day); 


    prefs = getSharedPreferences(prefName, MODE_PRIVATE); 
    SharedPreferences.Editor editor = prefs.edit(); 

    //---save the values in the EditText view to preferences--- 
     editor.putString(TITLE_KEY,"Muneeb's Notification"); 
     //---saves the values--- 
     editor.commit(); 

        scheduleClient.setAlarmForNotification(c);

//     Toast.makeText(this, "Notification set for: "+ day +"/"+ (month+1) +"/"+ year, Toast.LENGTH_SHORT).show();

}

Getting Error at this Line:

scheduleClient.setAlarmForNotification(c);

when I run the code the with hardcode values the c with become always null. (See the Image Below).

enter image description here

logcat

    04-21 10:07:39.430: E/AndroidRuntime(4721): FATAL EXCEPTION: main
04-21 10:07:39.430: E/AndroidRuntime(4721): Process: com.example.customnotification, PID: 4721
04-21 10:07:39.430: E/AndroidRuntime(4721): java.lang.RuntimeException: Unable to start activity ComponentInfo    {com.example.customnotification/com.example.customnotification.TestingActivity}: java.lang.NullPointerException
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.ActivityThread.access$800(ActivityThread.java:156)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.os.Looper.loop(Looper.java:157)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.ActivityThread.main(ActivityThread.java:5872)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at java.lang.reflect.Method.invokeNative(Native Method)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at java.lang.reflect.Method.invoke(Method.java:515)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at dalvik.system.NativeStart.main(Native Method)
04-21 10:07:39.430: E/AndroidRuntime(4721): Caused by: java.lang.NullPointerException
04-21 10:07:39.430: E/AndroidRuntime(4721):     at services.ScheduleClient.setAlarmForNotification(ScheduleClient.java:62)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at com.example.customnotification.TestingActivity.nofitication(TestingActivity.java:56)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at com.example.customnotification.TestingActivity.onCreate(TestingActivity.java:31)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.Activity.performCreate(Activity.java:5312)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
04-21 10:07:39.430: E/AndroidRuntime(4721):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
04-21 10:07:39.430: E/AndroidRuntime(4721):     ... 11 more

Solution

  • You cant set the calendar when service is not yet bound. You should rather listen to onServiceConnected.

    In your concrete example you should set the calendar in ScheduleClient.java:47 Thats the moment the service is connected and the calendar can be set.

    Something along the lines of (ScheduleClient.java):

    public class ScheduleClient {
    
    // The hook into our service
    private ScheduleService mBoundService;
    // The context to start the service in
    private Context mContext;
    // A flag if we are connected to the service or not
    private boolean mIsBound;
    
    public ScheduleClient(Context context) {
        mContext = context;
    }
    
    /**
     * Call this to connect your activity to your service
     */
    public void doBindService() {
        // Establish a connection with our service
        mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
    
    /**
     * When you attempt to connect to the service, this connection will be called with the result.
     * If we have successfully connected we instantiate our service object so that we can call methods on it.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with our service has been established, 
            // giving us the service object we can use to interact with our service.
            mBoundService = ((ScheduleService.ServiceBinder) service).getService();
            Calendar c = Calendar.getInstance();
            c.clear();
            int year = 2014;
            int month = 3;
            int day = 21;
            c.set(year, month, day);
            ScheduleClient.this.setAlarmForNotification(c);
        }
    
        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };
    
    /**
     * Tell our service to set an alarm for the given date
     * @param c a date to set the notification for
     */
    public void setAlarmForNotification(Calendar c){
        mBoundService.setAlarm(c);
    }
    
    /**
     * When you have finished with the service call this method to stop it 
     * releasing your connection and resources
     */
    public void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            mContext.unbindService(mConnection);
            mIsBound = false;
        }
    }
    

    }