2016-06-28 8 views
0

私はあなたが取る必要がありますまず第一Notification.classローダはのjava.lang.NullPointerException context.getSharedPreferences

ある
public Notification(Context context) { 
    this.context = context; 
    pref = context.getSharedPreferences(NOTIFICATION_SETTINGS_PREF_NAME, PRIVATE_MODE);//here is error (NullPointerException) 
    editor = pref.edit(); 
} 
+0

明らかに、フラグメントのライフサイクルを考慮する必要があります... – Selvin

答えて

0

@Override 
public void setMenuVisibility(final boolean visibility) { 
    super.setMenuVisibility(visibility); 

    if (visibility) { 

     Notification n = new Notification(getContext()); 

     if (n.getNewNotificationsCount() > 0) { 
      n.setNotificationsAsSeen(); 
      n.setNewNotificationsCount(0); 
     } 
    } 

} 

、フラグメントにNotification n = new Notification(getContext());を呼び出し、ここでnullpointerexception

を取得そのフラグメントはアクティビティにアタッチされた後にのみアクティビティContextを取得します。 onCreate()のフラグメントのライフサイクルメソッド以降で、onDetachedが呼び出された後ではなく、このメソッドを呼び出すことは安全です。 次に、API 23でFragmentのgetContext()メソッドが追加されたことを考慮する必要があります。したがって、APIの低いデバイスでSDKツール23を使用してアプリケーションビルドを実行すると、NullPointerExceptionが発生する可能性があります。

関連する問題