2016-07-13 61 views
-1

我試圖從兩個不同的活動接收兩種不同的意圖。我在接收活動的OnCreate中嘗試了以下方法:從兩個不同活動接收兩個意圖時出錯。

Intent intent1 = getIntent(); 
     if(intent1.getStringExtra("packagename").equals("com.example.kaad.calenderlearning.MainActivity")) { 
      DateString = intent1.getStringExtra("DATE"); 
      try { 
       DateFormat df = new SimpleDateFormat("MMM d,yyyy", Locale.ENGLISH); 
       date = df.parse(DateString); 
      } catch (ParseException e) { 
       e.printStackTrace(); 
      } 

      DateTextView.setText(DateString); 

      save = true; 
      correctintent = false; 
     } 
     else 
     { 
      Bundle extras = getIntent().getExtras(); 
      if (extras != null) 
      { 
       rowID = extras.getLong("row_id"); 
       AppointmentsEditText.setText(extras.getString("title")); 
       LocationNameEdit.setText(extras.getString("location")); 
       AppointmentDoctorEdit.setText(extras.getString("doctor")); 
       DateTextView.setText(extras.getString("date")); 
      } 
      if(getIntent().getExtras() == null) 
      { 
       save = true; 
      } 
      correctintent = true; 
      save = false; 
     } 

它在StringExtra存在於意圖中時起作用。但是,它不會去else語句。相反,它顯示了以下錯誤:

了java.lang.RuntimeException:無法啓動活動 ComponentInfo {com.example.kaad.calenderlearning/com.example.kaad.calenderlearning.MakeAppointmentsActivity}: 的java.lang .NullPointerException:嘗試調用虛擬方法 「布爾java.lang.String.equals(java.lang.Object中)」上的空對象 參考

我已經在這個題目研究。但是我的項目中沒有解決方案。我真的很感謝這個社區的幫助。

+0

可能重複http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do -我修復它 – SripadRaj

回答

0

首先檢查Intent是否包含包名稱! 如果包含然後只提取它, 如果不包含,那麼它將執行你的其他部分。

Intent intent1 = getIntent(); 

    if(intent1.hasExtra("packagename")){ 
        if(intent1.getStringExtra("packagename").equals("com.example.kaad.calenderlearning.MainActivity")) { 
       DateString = intent1.getStringExtra("DATE"); 
       try { 
        DateFormat df = new SimpleDateFormat("MMM d,yyyy", Locale.ENGLISH); 
        date = df.parse(DateString); 
       } catch (ParseException e) { 
        e.printStackTrace(); 
       } 

       DateTextView.setText(DateString); 

       save = true; 
       correctintent = false; 
      } 
    }//if(intent1.hasExtra("packagename")) closes here.... 
    else{ 
       Bundle extras = getIntent().getExtras(); 
       if (extras != null) 
       { 
        rowID = extras.getLong("row_id"); 
        AppointmentsEditText.setText(extras.getString("title")); 
        LocationNameEdit.setText(extras.getString("location")); 
        AppointmentDoctorEdit.setText(extras.getString("doctor")); 
        DateTextView.setText(extras.getString("date")); 
       } 
       if(getIntent().getExtras() == null) 
       { 
        save = true; 
       } 
       correctintent = true; 
       save = false; 
    } 
0

你可以這樣做,這樣既避免NullPointerException異常:

Intent intent1 = getIntent(); 
if ("com.example.kaad.calenderlearning.MainActivity".equals(intent1.getStringExtra("packagename")) {...} 
相關問題