My Application class is developed using Kotlin (I use Dagger2). In a class written in Java, I need to pass Context, but I get a nullpointerexception. How can I get Context?
My Application class:
class App : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.factory().create(this)
}
}
My Java Method:
public class NotificationUtil {
private static NotificationUtil instance;
public NotificationUtil() {
}
public static synchronized NotificationUtil getInstance() {
if (instance == null)
return new NotificationUtil();
return instance;
}
public void postNotificationSpam(StatusBarNotification sbn, int numberNotify) {
Context context = new App().getApplicationContext();
NotificationCompat.Builder ncb;
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
}
I'm trying to call a method in an Activity like this:
NotificationUtil.getInstance().postNotificationSpam(lstNotify.get(0).barNotification, lstNotify.size());
My error code:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.package.cleanapp.service.NotificationUtil.postNotificationSpam(NotificationUtil.java:204)
CodePudding user response:
You are using new App().getApplicationContext();.Do not use this.Because your app is opened,but not initialized.Instead you can use this
.
CodePudding user response:
I solved the problem by passing the context through the constructor
public void postNotificationSpam(Context context, StatusBarNotification sbn, int numberNotify) {
NotificationCompat.Builder ncb;
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
In Activity:
NotificationUtil.getInstance().postNotificationSpam(this, lstNotify.get(0).barNotification, lstNotify.size());