What could be the problem? I want to implement a general class for notifications, here ->

package com.example.artem_molodcov.twoontwo; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class NotificationClass extends AppCompatActivity { //id notify private static final int NOTIFY_ID = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void notificationCreate(String act) { String notify_title = "Уведомление", notify_text = ""; switch (act) { case "authTrue": notify_text = "Авторизация прошла успешно."; break; default: notify_text = "Что-то то приключилось у вас."; break; } Context context = getApplicationContext(); Intent notificationIntent = new Intent(context, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); Resources res = context.getResources(); Notification.Builder builder = new Notification.Builder(context); builder.setContentIntent(contentIntent) .setSmallIcon(R.drawable.ic_notifications_white_18dp) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(notify_title) .setContentText(notify_text); Notification notification = builder.build(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFY_ID, notification); } } 

If the code specified in the notificationCrate inserted not as a class, but as usual, then everything works, and if so:

  NotificationClass notificationClass = new NotificationClass(); notificationClass.notificationCreate("authTrue"); 

That application crashes. Tell me what's wrong.

    1 answer 1

    You get a NullPointerException. getApplicationContext() method returns null By creating an activity in this way, you do not tie it to the system and it does not have access to the context.

    Decision:

    1. Your utility class should not inherit activations.
    2. The context must be passed to the method as an argument and a reference to it is used.

     public class NotificationClass { //id notify private static final int NOTIFY_ID = 101; public void notificationCreate(Context ctx, String act) { //теперь ctx не null ... } } 

    To call in a class activit like this:

     NotificationClass notificationClass = new NotificationClass(); notificationClass.notificationCreate(this, "authTrue");