简体   繁体   中英

Alerts getting error android

I am trying to have an alert appear on a certain time. I was able to do that, but when I press the snooze button it works, I get another alert but I also get some errors. Find the errors below:

11-19 12:50:26.755: E/AndroidRuntime(452): FATAL EXCEPTION: main
11-19 12:50:26.755: E/AndroidRuntime(452): java.lang.NullPointerException
11-19 12:50:26.755: E/AndroidRuntime(452):  at android.app.PendingIntent.getActivity(PendingIntent.java:191)
11-19 12:50:26.755: E/AndroidRuntime(452):  at com.example.servicealarmdemo2.MainActivity.repeat(MainActivity.java:124)
11-19 12:50:26.755: E/AndroidRuntime(452):  at com.example.servicealarmdemo2.AlertDemo$2.onClick(AlertDemo.java:58)
11-19 12:50:26.755: E/AndroidRuntime(452):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
11-19 12:50:26.755: E/AndroidRuntime(452):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 12:50:26.755: E/AndroidRuntime(452):  at android.os.Looper.loop(Looper.java:123)
11-19 12:50:26.755: E/AndroidRuntime(452):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-19 12:50:26.755: E/AndroidRuntime(452):  at java.lang.reflect.Method.invokeNative(Native Method)
11-19 12:50:26.755: E/AndroidRuntime(452):  at java.lang.reflect.Method.invoke(Method.java:507)
11-19 12:50:26.755: E/AndroidRuntime(452):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-19 12:50:26.755: E/AndroidRuntime(452):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-19 12:50:26.755: E/AndroidRuntime(452):  at dalvik.system.NativeStart.main(Native Method)

the function that repeats the alert is in MainActivity.java

public  void repeat() {
        Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
        PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
        AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
        long time= System.currentTimeMillis();
        EditText text=(EditText)findViewById(R.id.editText1);
        String str = text.getText().toString();
        long t=Long.parseLong(str);
        alarmManager.set(AlarmManager.RTC_WAKEUP, time+( t*60*1000), operation);
}

and the following two classes are for the alerts:

AlertDemo.java

package com.example.servicealarmdemo2;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;



import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;


public class AlertDemo extends DialogFragment  {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        /** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
        getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);


        /** Creating a alert dialog builder */
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        /** Setting title for the alert dialog */
        builder.setTitle("Alarm");

        /** Setting the content for the alert dialog */
        builder.setMessage("An Alarm by AlarmManager");

        /** Defining an OK button event listener */
        builder.setPositiveButton("Take", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                /** Exit application on click OK */
                getActivity().finish();
            }                       
        });

        builder.setNegativeButton("Snooze", new OnClickListener()  {
        //  @Override

            public void onClick(DialogInterface dialog, int which) {
                /** Exit application on click OK */
                //getActivity().finish();

//           repeat();

                System.out.println("REPEAT");
                new MainActivity().repeat();
                //System.out.println("Activities: "+m);


            }
        });
        /** Creating the alert dialog window */
        return builder.create();
    }

    /** The application should be exit, if the user presses the back button */ 
    @Override
    public void onDestroy() {       
        super.onDestroy();
        getActivity().finish();
    }

//      public  void  repeat() {
//          MainActivity.repeat();
//      }


//  public  void repeat() {
//      Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
////        PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
//      PendingIntent operation = PendingIntent.getActivity(getActivity().getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
//      AlarmManager alarmManager = (AlarmManager) getActivity().getBaseContext().getSystemService(getActivity().ALARM_SERVICE);
//      long time= System.currentTimeMillis();
//      EditText text=(EditText)getActivity().findViewById(R.id.editText1);
//      String str = text.getText().toString();
//      long t=Long.parseLong(str);
//       alarmManager.set(AlarmManager.RTC_WAKEUP, time+( t*60*1000), operation);
//      
//    }

}

and DemoActivity.java

package com.example.servicealarmdemo2;



import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

public class DemoActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState); 

        /** Creating an Alert Dialog Window */
        AlertDemo alert = new AlertDemo();

        /** Opening the Alert Dialog Window */
        alert.show(getSupportFragmentManager(), "AlertDemo");       
    }
}
new MainActivity().repeat();

Never instantiate activities using new , only via Intent .

Reason for NPE is that the code is trying to use the activity as a Context but it has not been properly initialized for such use.

Technically, getBaseContext() returns null and getActivity() unconditionally calls a method on the passed-in context.

The way you did code its not look good, and Null-pointer is because of wrong Context .

PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);

Try to pass activity context while calling repeat() function.

new MainActivity().repeat(Activity context); //pass here activity context.

public  void repeat(Activity ctx) {
        Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
        PendingIntent operation = PendingIntent.getActivity(ctx, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
.
.
.
.
}

But not a good way to achieve!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM