How to get Context from Kotlin file in Java file?

Published

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)

Source: Android Questions

Published
Categorized as android, android-context, dagger-2, java, kotlin

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq