Android中BroadCastService类中的Nullpointer异常

时间:2014-08-19 12:40:21

标签: android broadcastreceiver alarmmanager

我必须在特定日期发送电子邮件,这就是为什么我使用BroadcastReceiver类。但是当我运行应用程序时它会崩溃并在行= Intent intent = new Intent(上下文,AlarmManagerBroadcastReceiver)获取NullPointerException。有人可以帮我,请你怎么做。谢谢。

这是我的代码

public class Xyz extends Activity
{
    EditText etServiceName;
    EditText etSupplierName;
    EditText etEmailId;
    EditText etReplacementDate;
    EditText etInterval_Days;
    EditText etNextReplanishmentDate;
    Button btnSubmit;

    String strServiceName;
    String strSuppliername;
    String strEmail;
    String strReplacementDate;
    String strIntervalDays;
    String strNextReplacementDate;

    String body;
    Date convertedDate;
    int interval_days;
    private int year;
    private int month;
    private int day;
    int i;
    static final int DATE_OF_REPLACEMENT = 1111;
    int intConvertDays;
    String strMinusDate;
    int IntMinusDate;

    Context context;
    Calendar cal=Calendar.getInstance();

    Database_Helper databaseHelper;
    SQLiteDatabase db;

    public void onCreate(Bundle savedInstanceState)
    {

etInterval_Days.addTextChangedListener(new TextWatcher(){

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable editable) 
                {
                    // TODO Auto-generated method stub
                     String fixedDate = etReplacementDate.getText().toString().trim();
                     SimpleDateFormat dateFormat1 = new SimpleDateFormat( "dd-MM-yyyy" );
                       Calendar cal = Calendar.getInstance();
                       try
                       {
                                cal.setTime( dateFormat1.parse( fixedDate ) );
                       } 
                       catch (ParseException e) 
                       {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                       }

                       String strNumDays = etInterval_Days.getText().toString().trim();
                       if(strNumDays.trim().length()>0)
                       {
                           try
                              { 
                                  intConvertDays =Integer.valueOf(strNumDays);
                              }
                              catch(NumberFormatException ne)
                              {
                                 System.out.println("could not parse :: " +ne);
                              }

                       }

                        cal.add( Calendar.DATE, intConvertDays );
                       Date dated = cal.getTime();
                       String beforDate_String = new SimpleDateFormat("dd-MM-yyyy").format(dated);
                       System.out.println("beforDate_String: " + beforDate_String);
                       etNextReplanishmentDate.setText(beforDate_String);

                       cal.add( Calendar.DATE, -2 );
                       Date minusDate = cal.getTime();
                       strMinusDate = new SimpleDateFormat("dd-MM-yyyy").format(minusDate);
                       System.out.println("String strMinusDate : " + strMinusDate);



                       if(strMinusDate.trim().length()>0)
                       {
                           try
                              { 
                                IntMinusDate =Integer.valueOf(strMinusDate);
                                System.out.println(" IntMinusDate = " + IntMinusDate);
                              }
                              catch(NumberFormatException ne)
                              {
                                 System.out.println("could not parse :: " +ne);
                              }

                       }
                  }
            });


         btnSubmit = (Button) findViewById(R.id.buttonSubmit);
         btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                 strEmail= etEmailId.getText().toString().trim();


                         strServiceName =  etServiceName.getText().toString().trim();
                         strSuppliername= etSupplierName.getText().toString().trim();
                         strReplacementDate= etReplacementDate.getText().toString().trim();
                         strIntervalDays= etInterval_Days.getText().toString().trim();
                         strNextReplacementDate = etNextReplanishmentDate.getText().toString().trim();
                         System.out.println("Data :- " + strServiceName +","+ strSuppliername +","+ strEmail +","+ strReplacementDate +","+ strIntervalDays + "," + strNextReplacementDate+" , "+strMinusDate);

                         SharedPreferences sharedPref =getSharedPreferences("MyPref_Email", 0);
                         SharedPreferences.Editor editor1 = sharedPref.edit();

                         editor1.putString("ServiceName", strServiceName);
                         editor1.putString("Suppliername", strSuppliername);
                         editor1.putString("Email", strEmail);
                         editor1.putString("ReplacementDate", strReplacementDate);
                         editor1.putString("IntervalDays", strIntervalDays);
                         editor1.putString("NextReplacementDate", strNextReplacementDate);
                         editor1.putString("EmailDate", strMinusDate);

                         editor1.commit();
                         Log.e("Commit is Complit", "Save");

                         //sendEmail();
                         System.out.println("Email Has To Be Sent Successfully");

                         databaseHelper.insertServicenDetails(strServiceName, strSuppliername, strEmail, strReplacementDate, strIntervalDays, strNextReplacementDate);
                         System.out.println("Data Has Been Save Successfully");



                            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm");
                            long millis = 0;
                            try {
                                millis = format.parse(strMinusDate).getTime();
                                System.out.println("millis  = " + millis);
                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            cal.isSet((int) millis);

                            AlarmManager alarmManager = (AlarmManager) Xyz.this.getSystemService(Context.ALARM_SERVICE);
                            Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
                            PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
                            alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pi);
                            Log.d("Testing", "alarm manager set");



              }
        });




Here is AlarmManagerBroadcastReceiver class
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver 
{
    String strServiceName;
    String strSuppliername;
    String strEmail;
    String strReplacementDate;
    String strIntervalDays;
    String strNextReplacementDate;
    String strEmailDate;

    @Override
    public void onReceive(Context con, Intent arg1)
    {
        // TODO Auto-generated method stub
         SharedPreferences prefs = con.getSharedPreferences("MyPref_CellNumber", Context.MODE_PRIVATE);
         SharedPreferences.Editor editor1 = prefs.edit();

         strServiceName=prefs.getString("ServiceName", "a/n");
         strSuppliername=prefs.getString("Suppliername" , "a/n");
         strEmail=prefs.getString("Email" , "a/n");
         strReplacementDate=prefs.getString("ReplacementDate" , "a/n");
         strIntervalDays=prefs.getString("IntervalDays" , "a/n");
         strNextReplacementDate=prefs.getString("NextReplacementDate" , "a/n");
         strEmailDate = prefs.getString("EmailDate", "a/n");

         System.out.println(strServiceName+" , "+strSuppliername+" , "+strEmail+" , "+strReplacementDate+" , "+strIntervalDays+" , "+strNextReplacementDate);

         Log.e("ON CREATE" , "=" + strServiceName);
         Log.e("ON CREATE" , "=" + strSuppliername);
         Log.e("ON CREATE" , "=" + strEmail);
         Log.e("ON CREATE" , "=" + strReplacementDate);
         Log.e("ON CREATE" , "=" + strIntervalDays);
         Log.e("ON CREATE" , "=" + strNextReplacementDate);
         Log.e("ON CREATE" , "=" + strEmailDate);


        String subject =strServiceName;

        String body = strServiceName
                      +","
                      +strSuppliername
                      +","
                      +strEmail
                      +","
                      +strReplacementDate
                      +","
                      +strIntervalDays
                      +","
                      +strNextReplacementDate
                      +","
                      +strEmailDate;

                          Log.e("body " , " = " + body);

                          Intent i = new Intent(Intent.ACTION_SEND);
                          i.setType("message/rfc822");
                        //  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                          i.putExtra(Intent.EXTRA_EMAIL  , new String[]{strEmail});
                          i.putExtra(Intent.EXTRA_SUBJECT, subject);
                          i.putExtra(Intent.EXTRA_TEXT   , body);
                          con.startActivity(Intent.createChooser(i, "Share viaSend mail...in Service Background"));
                          Log.e("Send Email ="," In My Service  ");
                          System.out.println("Service start time");

    }

}


Here is log cat
08-19 18:03:00.396: E/AndroidRuntime(1555): FATAL EXCEPTION: main
08-19 18:03:00.396: E/AndroidRuntime(1555): java.lang.NullPointerException
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.content.ComponentName.<init>(ComponentName.java:75)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.content.Intent.<init>(Intent.java:2702)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at com.demo.Xyz$4.onClick(Xyz.java:282)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.view.View.performClick(View.java:2485)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.view.View$PerformClick.run(View.java:9080)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.os.Handler.handleCallback(Handler.java:587)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.os.Looper.loop(Looper.java:123)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at android.app.ActivityThread.main(ActivityThread.java:3683)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at java.lang.reflect.Method.invokeNative(Native Method)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at java.lang.reflect.Method.invoke(Method.java:507)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-19 18:03:00.396: E/AndroidRuntime(1555):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您说您已在Activity类中的onCreate()方法之前初始化了contet。

事实上,从发布的代码上下文刚刚声明从未初始化。

Context context; // declared

一旦创建了活动,就可以使用上下文。在onCreate初始化上下文。

在onCreate

Context context;
@Override
public void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.yourlayout);
   context = this; 
   ...// rest of the code

编辑:

   Intent i = new Intent(Intent.ACTION_SEND);
   i.setType("message/rfc822");
   i.putExtra(Intent.EXTRA_EMAIL  , new String[]{strEmail});
   i.putExtra(Intent.EXTRA_SUBJECT, subject);
   i.putExtra(Intent.EXTRA_TEXT   , body);
   i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   con.startActivity(Intent.createChooser(i, "Share viaSend mail...in Service Background"));