VKDev
VKDev

Reputation: 604

Get application instance returns null

I have no ideas, but...

public class MyApplication extends MultiDexApplication {
    public MyApplication() {//for example, here
        instance = this;
    }

     @Override
    public void onCreate() { //or here
        instance = this;
        super.onCreate();
    }
}

in my activity

@Override
    protected void onPause() {//onStart, onCreate, etc 
        MyApplication.getInstance().doSomething();
        super.onPause();
    }

And in random moments I have the crash.

FATAL EXCEPTION: main
        Process: com.mypackage.myapplication, PID: 17579
        java.lang.RuntimeException: Unable to pause activity {com.mypackage.myapplication.MyFragmentActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mypackage.myapplication.MyApplication.getInstance().doSomething()' on a null object reference

ie MyApplication.getInstance returns null! How do you think, what the... issue? Using debug in AndroidStudio 2.0

Upvotes: 1

Views: 4197

Answers (2)

peeyush pathak
peeyush pathak

Reputation: 3663

don't keep the instance as static in application class. you can use

(MyApplication) getApplicationContext()

this will get you your application object.

just dont typecast the activity object to MainApplication class directly.

in case of Test case you can change it to getApplicationContext()

Upvotes: 1

Manikanta
Manikanta

Reputation: 3421

It looks like you want application context to perform some operations, I Don't know why you need your own application instance. Use getApplicationContext(); to get context

Another solution is to define your application class in your manifest under application tag

android:name=".MyApplication"

Comment below for any further information

Upvotes: 2

Related Questions