title: Implementing NotificationListenerService in android
body: <p>I wanted to display notifications that are posted by other applications in the status bar. So I made a button. Clicking the button would call <code>executeButtonClick()</code> method. <strong>My code</strong> :</p>
  
  <pre><code>public void executeButtonClick(View view) {
      NLService nlService = new NLService();
      if(nlService.getActiveNotifications()!=null) {
          Toast.makeText(MainActivity.this,"InsideIf",Toast.LENGTH_SHORT).show();
          for (StatusBarNotification sbn : nlService.getActiveNotifications()) {
              String temp = "Package Name: " + sbn.getPackageName() +
                      "\n" + "Title: " + sbn.getNotification().extras.getString("android.title") + "\n" +
                      "Text: " + sbn.getNotification().extras.getCharSequence("android.text");
              String newText = textView.getText().toString() + temp;
              textView.setText(newText);
  
          }
      }
  }
  </code></pre>
  
  <p>But the notification is not shown and I am getting null pointer exception:</p>
  
  <p><code>"Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference"</code></p>
  
  <p>in the following line: <code>activity.executeButtonClick(com.example.asus.notificationtest.MainActivity.textView);</code></p>
  
  <p>of the <code>onNotificationPosted()</code> method mentioned below:</p>
  
  <pre><code>public class NLService extends NotificationListenerService {
  
  Context context;
  
  @Override
  public void onCreate() {
      super.onCreate();
      context = getApplicationContext();
  }
  
  @Override
  public void onNotificationPosted(StatusBarNotification sbn) {
      if(MainActivity.textView != null)
          activity.executeButtonClick(com.example.asus.notificationtest.MainActivity.textView);
      //Toast.makeText(this,"Post from: "+sbn.getPackageName(),Toast.LENGTH_SHORT).show();
  }
  
  @Override
  public void onNotificationRemoved(StatusBarNotification sbn) {
      //Toast.makeText(this,"Post from: "+sbn.getPackageName(),Toast.LENGTH_SHORT).show();
  }
  </code></pre>