2

I am trying to add a pending intent from onClick of a button to implement alarm but I am getting a null pointer exception "at android:app.PendingIntent.getActivity(PendingIntent.java:257)" and "at android:app.PendingIntent.getActivity(PendingIntent.java:224)".

Here's my code where on click of the "ADD" button is supposed to create the Pending Intent.

public class DisplayAlertMessage extends Activity {
private int mYear, mMonth, mDay, mHour, mMinute;
private long alarm_time;
    private int rem = 0;
    private String date,time;
    private String lists1[] = new String[10];
static final int DATE_DIALOG_ID = 999;

@SuppressLint("InflateParams") 
public void displayAlertDialog(LayoutInflater inflater,final MainActivity obj,final MainActivity obj1,final Context con) {
    /** This intent invokes the activity DemoActivity, which in turn opens the AlertDialog window */
    final Intent in = new Intent("com.example.todotry_1.demoactivity");
     final View alertLayout = inflater.inflate(R.layout.layout_custom_dialog, null);
     final EditText Note = (EditText) alertLayout.findViewById(R.id.Note);
     final EditText Lists = (EditText) alertLayout.findViewById(R.id.Lists);
     final TextView Remind = (TextView) alertLayout.findViewById(R.id.Remind);
     final TextView Time = (TextView) alertLayout.findViewById(R.id.Time);
     final TextView Date = (TextView) alertLayout.findViewById(R.id.Date);
     final TextView Timeval = (TextView) alertLayout.findViewById(R.id.Timeval);
     final TextView Dateval = (TextView) alertLayout.findViewById(R.id.Dateval);
     final ImageView iv=(ImageView) alertLayout.findViewById(R.id.img);
     i=iv;
     AlertDialog.Builder alert = new AlertDialog.Builder(obj,R.style.DialogTheme);
     Remind.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Log.d("onCLICK","REMIND");
               Toast.makeText(con, "REMIND CLICKED", Toast.LENGTH_SHORT).show();
               Remind.setVisibility(View.GONE);
               Time.setVisibility(View.VISIBLE);
               Date.setVisibility(View.VISIBLE);
               rem = 1;
               Time.setOnClickListener(new OnClickListener() {
                @Override
                            public void onClick(View v) {
                            final Calendar c = Calendar.getInstance();
                                mHour = c.get(Calendar.HOUR_OF_DAY);
                                mMinute = c.get(Calendar.MINUTE);

                                // Launch Time Picker Dialog
                                TimePickerDialog tpd = new TimePickerDialog(obj,new TimePickerDialog.OnTimeSetListener() 
                                {

                                            @Override
                                            public void onTimeSet(TimePicker view, int hourOfDay,int minute) {
                                             // Display Selected time in textbox
                                            Timeval.setVisibility(View.VISIBLE);
                                                Timeval.setText(hourOfDay + ":" + minute);
                                            }
                                        }, mHour, mMinute, false);
                                    tpd.show();
                                    time = mHour+":"+mMinute;
                            }
                    });
               Date.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            final Calendar c = Calendar.getInstance();
                                mYear = c.get(Calendar.YEAR);
                                mMonth = c.get(Calendar.MONTH);
                                mDay = c.get(Calendar.DAY_OF_MONTH);

                            // Launch Date Picker Dialog
                            DatePickerDialog dpd = new DatePickerDialog(obj,new DatePickerDialog.OnDateSetListener() {
                @Override
                                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                            // Display Selected date in textbox
                                        Dateval.setVisibility(View.VISIBLE);
                                            Dateval.setText(dayOfMonth + "-"+ (monthOfYear + 1) + "-" + year);
                }
                                    }, mYear, mMonth, mDay);
                                dpd.show();
                                date = mDay+"-"+mMonth+"-"+mYear;
                            }
                    });
               GregorianCalendar calendar = new GregorianCalendar(mYear,mMonth,mDay, mHour, mMinute);
               alarm_time = calendar.getTimeInMillis();
           }
        });


     alert.setTitle("ADD NOTE");
     alert.setView(alertLayout);
     alert.setCancelable(false);
     alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
     Toast.makeText(con, "Cancel clicked", Toast.LENGTH_SHORT).show();
     }
     });

     alert.setPositiveButton("ADD", new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
     // code for matching password
     String note = Note.getText().toString();
     String lists = Lists.getText().toString() + '\n';

     int l=lists.length();
     int i=0;
     String one="";
     char q;
     String main1="";
     int count = 0,j=0;
     for (i=0;i<l;i++)
     {
         q=lists.charAt(i);
         if(q!='\n' )
             one += q;
         else
         { 
             Log.d("the string",":" + one);
             //Toast.makeText(getBaseContext(), "Words " + one , Toast.LENGTH_SHORT).show();
             main1 += count + " : " + one;
             lists1[j++] = one;
             one=""; 
         }
         count++;
     }
     Log.d("DISplay","111before finish add");
     if((date == null)^(time == null))
     {
         Toast.makeText(con, "Enter both date and time to set alarm", Toast.LENGTH_SHORT).show();
     }
     else{
     TaskDBHelper ob = new TaskDBHelper(obj1);
     SQLiteDatabase sqlDB = ob.getWritableDatabase();
     if((date != null)&(time != null))
     {
         String f1 = String.format("INSERT INTO prioritised (task,date,time,ringtone,done,Hidden) VALUES('"+note+"','"+date+"','"+time+"','"+""+"',0,"+MainActivity.getStat()+")");
         sqlDB.execSQL(f1);
         if((j!=0)&(main1!="\n") )
         {
             int id=0;
             Cursor cursor = sqlDB.rawQuery("SELECT _id from prioritised where task = '"+note+"'",null);

             if (cursor != null) {
                    try {
                        if (cursor.moveToFirst()) {
                            id = cursor.getInt(0);
                        }
                    } finally {
                        cursor.close();
                    }
                }
             Log.d("Prio"," "+id);
             String add;
             for(int k=0;k<j;k++)
             {
                 add = String.format("INSERT INTO sublistprioritised (_id1,sublist,done,hidden) VALUES("+id+",'"+lists1[k]+"',0,"+MainActivity.getStat()+")");
                 sqlDB.execSQL(add);
             }

         }

            /** Creating a Pending Intent */
            Context x=getBaseContext();
                            int requestID = (int) System.currentTimeMillis();
            PendingIntent operation = PendingIntent.getActivity(x, requestID, in,Intent.FLAG_ACTIVITY_NEW_TASK);

            /** Getting a reference to the System Service ALARM_SERVICE */
            AlarmManager alarmManager = (AlarmManager) x.getSystemService(ALARM_SERVICE);

            /** Setting an alarm, which invokes the operation at alart_time */
                    alarmManager.set(AlarmManager.RTC_WAKEUP  , alarm_time , operation);
                    /** Alert is set successfully */
                    Toast.makeText(x, "Alarm is set successfully",Toast.LENGTH_SHORT).show();
     }
     else{
     String f2 = String.format("INSERT INTO unprioritised (task,done,Hidden) VALUES('"+note+"',0,"+MainActivity.getStat()+")");
     sqlDB.execSQL(f2);
     if((j!=0)&(main1!="\n") )
     {
         int id=0;
         Cursor cursor = sqlDB.rawQuery("SELECT _id from unprioritised where task = '"+note+"'",null);
         if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        id = cursor.getInt(0);
                    }
                } finally {
                    cursor.close();
                }
            }
         String add;
         for(int k=0;k<j;k++)
         {
             add = String.format("INSERT INTO sublistunprioritised (_id1,sublist,done,Hidden) VALUES("+id+",'"+lists1[k]+"',0,"+MainActivity.getStat()+")");
             sqlDB.execSQL(add);
         }

     }
     }
     }
     }
     });
     AlertDialog dialog = alert.create();
     dialog.show();
     }
}

Thank You. Any help is appreciated.

Here's the Logcat

04-02 13:38:03.922: E/AndroidRuntime(2120): FATAL EXCEPTION: main
04-02 13:38:03.922: E/AndroidRuntime(2120): Process: com.example.todotry_1, PID: 2120
04-02 13:38:03.922: E/AndroidRuntime(2120): java.lang.NullPointerException
04-02 13:38:03.922: E/AndroidRuntime(2120): at android.app.PendingIntent.getActivity(PendingIntent.java:257)
04-02 13:38:03.922: E/AndroidRuntime(2120): at android.app.PendingIntent.getActivity(PendingIntent.java:224)
04-02 13:38:03.922: E/AndroidRuntime(2120): at com.example.todotry_1.DisplayAlertMessage$4.onClick(DisplayAlertMessage.java:244)
04-02 13:38:03.922: E/AndroidRuntime(2120): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
04-02 13:38:03.922: E/AndroidRuntime(2120): at android.os.Handler.dispatchMessage(Handler.java:102)
04-02 13:38:03.922: E/AndroidRuntime(2120): at android.os.Looper.loop(Looper.java:136)
04-02 13:38:03.922: E/AndroidRuntime(2120): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-02 13:38:03.922: E/AndroidRuntime(2120): at java.lang.reflect.Method.invokeNative(Native Method)
04-02 13:38:03.922: E/AndroidRuntime(2120): at java.lang.reflect.Method.invoke(Method.java:515)
04-02 13:38:03.922: E/AndroidRuntime(2120): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-02 13:38:03.922: E/AndroidRuntime(2120): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-02 13:38:03.922: E/AndroidRuntime(2120): at dalvik.system.NativeStart.main(Native Method)

Updated log:

04-02 15:59:03.140: E/AndroidRuntime(1880): android.database.sqlite.SQLiteConstraintException: columns _id1, sublist are not unique (code 19)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:734)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
04-02 15:59:03.140: E/AndroidRuntime(1880): at com.example.todotry_1.DisplayAlertMessage$4.onClick(DisplayAlertMessage.java:236)
04-02 15:59:03.140: E/AndroidRuntime(1880): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.os.Handler.dispatchMessage(Handler.java:102)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.os.Looper.loop(Looper.java:136)
04-02 15:59:03.140: E/AndroidRuntime(1880): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-02 15:59:03.140: E/AndroidRuntime(1880): at java.lang.reflect.Method.invokeNative(Native Method)
04-02 15:59:03.140: E/AndroidRuntime(1880): at java.lang.reflect.Method.invoke(Method.java:515)
04-02 15:59:03.140: E/AndroidRuntime(1880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-02 15:59:03.140: E/AndroidRuntime(1880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-02 15:59:03.140: E/AndroidRuntime(1880): at dalvik.system.NativeStart.main(Native Method)
  • logcat data would be more useful.. – Karan Apr 02 '15 at 18:12
  • Edit: Logcat data added to the question – user3528608 Apr 02 '15 at 18:38
  • line 224 from PendingIntent.java is "public static PendingIntent getBroadcast(Context context, int requestCode,Intent intent, int flags) " the following method which confuses me even more as it isn't called. – user3528608 Apr 02 '15 at 18:42
  • It looks like you're trying to insert duplicate values for the primay keys in your table. See here: http://stackoverflow.com/questions/14818246/android-sqlite-columns-are-not-unique It looks like the PendingIntent code is working now though. Try uninstalling/re-installing and see if you get the database error on first run. – Daniel Nugent Apr 02 '15 at 20:29

1 Answers1

1

It looks like it's unnecessary to call getBaseContext() here, and you probably don't want to use the currentTimeMillis() as the requestCode, just in case you ever need to cancel the PendingIntent:

/** Creating a Pending Intent */
            //Context x=getBaseContext();
            //int requestID = (int) System.currentTimeMillis();

            PendingIntent operation = null;
            //Make sure nothing is null for debugging purposes
            if (con == null){
                Log.e("onCLICK","con is null");
            }
            else if (in == null){
                Log.e("onCLICK","in is null");
            }
            else{
                operation = PendingIntent.getActivity(con, 0, in,PendingIntent.FLAG_UPDATE_CURRENT);
            }

            if (operation != null){
               /** Getting a reference to the System Service ALARM_SERVICE */
               AlarmManager alarmManager = (AlarmManager) con.getSystemService(ALARM_SERVICE);

               /** Setting an alarm, which invokes the operation at alart_time */
                alarmManager.set(AlarmManager.RTC_WAKEUP  , alarm_time , operation);
                /** Alert is set successfully */
                Toast.makeText(con, "Alarm is set successfully",Toast.LENGTH_SHORT).show();

            }

Take a look at this post as well for examples: PendingIntent works correctly for the first notification but incorrectly for the rest

Edit: I just put the PendingIntent code into AndroidStudio, and it gave me this message:

Must be one or more of: PendingIntent.FLAG_ONE_SHOT, PendingIntent.FLAG_NO_CREATE, PendingIntent.FLAG_CANCEL_CURRENT, PendingIntent.FLAG_UPDATE_CURRENT, Intent.FILL_IN_ACTION, Intent.FILL_IN_DATA, Intent.FILL_IN_CATEGORIES, Intent.FILL_IN_COMPONENT, Intent.FILL_IN_PACKAGE, Intent.FILL_IN_SOURCE_BOUNDS, Intent.FILL_IN_SELECTOR, Intent.FILL_IN_CLIP_DATA less... (Ctrl+F1) Reports two types of problems: Supplying the wrong type of resource identifier. For example, when calling Resources.getString(int id), you should be passing R.string.something, not R.drawable.something. Passing the wrong constant to a method which expects one of a specific set of constants. For example, when calling View#setLayoutDirection, the parameter must be android.view.View.LAYOUT_DIRECTION_LTR or android.view.View.LAYOUT_DIRECTION_RTL.

Take a look at The Documentation for more info on valid flags to use here.

Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
  • Thanks for replying. Hey can you please repost the link for examples? – user3528608 Apr 02 '15 at 18:57
  • The intent is declared as in the android manifest. – user3528608 Apr 02 '15 at 19:07
  • @user3528608 is it `demoactivity` or `DemoActivity`? Hmm, if that is the action, then what is the Activity associated with that intent filter? – Daniel Nugent Apr 02 '15 at 19:08
  • I see. It's probably ok then. Try adding the code to make sure nothing is null before you use it, and see if you find anything. It might have been your `Context` that was null. – Daniel Nugent Apr 02 '15 at 19:19
  • Neither the context nor the intent return null. – user3528608 Apr 02 '15 at 19:26
  • @user3528608 It looks like the flag `Intent.FLAG_ACTIVITY_NEW_TASK` is not valid for use in `getActivity()` of `PendingIntent`, take a look at the updated answer. – Daniel Nugent Apr 02 '15 at 19:56
  • On changing the flag to PendingIntent.FLAG_UPDATE_CURRENT, the logcat gives me the following error android.database.sqlite.SQLiteConstraintException: columns _id1, sublist are not unique .... Does this mean that my null pointer is due to some database issue? – user3528608 Apr 02 '15 at 20:04
  • @user3528608 can you add the new logs to your question (but keep everything else there). It looks like possibly the original issue is fixed, and now it's failing on something else. – Daniel Nugent Apr 02 '15 at 20:10
  • @user3528608 Since the NullPointerException is no longer happening, it's probably best to just mark this answer as accepted since it solved it, and open up a new question on the database issue if you can't figure it out from looking at existing answers to other questions. There are a lot of questions about your database error with good answers. – Daniel Nugent Apr 02 '15 at 21:38