Home > Net >  Android Studio null object reference when creating
Android Studio null object reference when creating

Time:04-13

I am creating the class object before using it to set a variable in the class but I still get the null reference error. Why is this happeing?

public void onCreate() {
        MainActivity ma = new MainActivity();
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if(ma.isWalking) {
                    Log.i("walk","walking");
                }

CodePudding user response:

You absolutely positively cannot create an Activity like this:

MainActivity ma = new MainActivity();

Only the Android framework can instantiate Android components (Activity, Service, etc.)

Just use public static variables for this purpose which can be accessed from any class.

  • Related