使用警报管理器时出现java.lang.NullPointerException错误

时间:2013-03-27 08:43:31

标签: android alarm

当我使用警报管理器使用接收器发出通知时,显示此错误java.lang.NullPointerException

我从listView中选择一个项目然后调用setNotification方法,然后设置重复闹钟以触发通知。

这是代码:

public class TimesActivity extends OptionsMenu {

    ArrayList<String> getTiName = new ArrayList<String>();
    ArrayList<String> getTiTime = new ArrayList<String>();
    ArrayList<String> getTiBroad = new ArrayList<String>();
    ArrayList<String> getTiImg = new ArrayList<String>();

    public DAOTimes timeDatabase = null;
    int minutes;
    String prNameSelected;
    String prTimeSelected;
    Long now, start;
    int period;
    AlarmManager am;

    // =============================================================================

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listvideo);
        timeDatabase = new DAOTimes(this);
        getTimes();
        showTimes();
    }               

    // =============================================================================

    @Override
    protected Dialog onCreateDialog(int id) {

        switch (id) {
        case 0:
            // Create out AlterDialog
            final CharSequence[] array = { "5 min", "10 min", "15 min",
                    "45 min", "60 min" };
            Builder builder = new AlertDialog.Builder(this);

            builder.setCancelable(true);

            builder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                        }
                    });
            builder.setSingleChoiceItems(array, -1,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            if (array[which] == "1 min") {
                                minutes = 1;
                            } else if (array[which] == "10 min") {
                                minutes = 10;
                            } else if (array[which] == "15 min") {
                                minutes = 15;
                            } else if (array[which] == "45 min") {
                                minutes = 45;
                            } else if (array[which] == "60 min") {
                                minutes = 60;
                            }

                            dialog.dismiss();
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
        return super.onCreateDialog(id);
    }

    // =============================================================================

    public void setNotification() {
        Toast.makeText(TimesActivity.this, "result : ",
                Toast.LENGTH_LONG).show();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.MILLISECOND, period);

        Intent intent = new Intent(this, NotAlarm.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                30000, pendingIntent);



    }

    // =============================================================================

    public void showTimes() {
        final ListView listview = (ListView) findViewById(R.id.listView1);

        listview.setOnItemClickListener(new ListView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {                

                prNameSelected = getTiName.get(position);
                prTimeSelected = getTiTime.get(position);
                String date = getIntent().getStringExtra("DAY_DATE");

                SimpleDateFormat format = new SimpleDateFormat(
                        "yyyy-MM-dd, HH:mm:ss.SS");
                format.setLenient(false);

                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                int millisecond = calendar.get(Calendar.MILLISECOND);

                String time1 = year + "-" + (month + 1) + "-" + day + ", "
                        + hour + ":" + minute + ":" + second + "."
                        + millisecond;
                Date date1;
                try {
                    date1 = format.parse(time1);
                    now = date1.getTime();
                } catch (ParseException e) {                    
                    e.printStackTrace();
                }

                String time2 = date + ", " + prTimeSelected + ":00.00";
                Date date2;
                try {
                    date2 = format.parse(time2);
                    start = date2.getTime();
                } catch (ParseException e) {                    
                    e.printStackTrace();
                }

                int result = (int) (start - now);

                if (start > now) {
                    period = result;
                } else {
                    // period = start + (7 * 24 * 60 * 60 * 1000);
                }               

                Toast.makeText(TimesActivity.this, "result : " + period,
                        Toast.LENGTH_LONG).show();
                setNotification();
//              showDialog(0);
            }
        });

        listview.setAdapter(new TimesAdapter(TimesActivity.this, getTiName
                .toArray(new String[getTiName.size()]), getTiTime
                .toArray(new String[getTiTime.size()]), getTiBroad
                .toArray(new String[getTiBroad.size()]), getTiImg
                .toArray(new String[getTiImg.size()])));
    }
}

接收者活动:

package com.shadatv.shada;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NotAlarm extends BroadcastReceiver {

    NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        NotificationManager nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification.Builder builder = new Notification.Builder(context);
        builder.setSmallIcon(android.R.drawable.btn_star);
        builder.setTicker("notification");

        Notification notify = builder.getNotification();

        CharSequence title = "you have been notified";
        CharSequence details = "bvcburhvurh uhuh hghu hu";

        PendingIntent pending = PendingIntent
                .getActivity(context, 0, new Intent(), 0);
        notify.setLatestEventInfo(context, title, details, pending);

        nm.notify(0, notify);

    }

}

logcat的:

03-27 10:39:33.550: E/AndroidRuntime(3890): FATAL EXCEPTION: main
03-27 10:39:33.550: E/AndroidRuntime(3890): java.lang.NullPointerException
03-27 10:39:33.550: E/AndroidRuntime(3890):     at com.shadatv.shada.TimesActivity.setNotification(TimesActivity.java:161)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at com.shadatv.shada.TimesActivity$3.onItemClick(TimesActivity.java:228)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.widget.AdapterView.performItemClick(AdapterView.java:292)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.widget.AbsListView.performItemClick(AbsListView.java:1179)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2707)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.widget.AbsListView$1.run(AbsListView.java:3462)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.os.Handler.handleCallback(Handler.java:605)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.os.Looper.loop(Looper.java:137)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at android.app.ActivityThread.main(ActivityThread.java:4507)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at java.lang.reflect.Method.invokeNative(Native Method)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at java.lang.reflect.Method.invoke(Method.java:511)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-27 10:39:33.550: E/AndroidRuntime(3890):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

您忘记初始化am闹钟管理器。

像这样初始化它。

AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);