NullPointerException: android.content.Context.getPackageName() on a null object reference

  android, java, nullpointerexception

I’m trying to call MainActivity.my_method() from a different class, but I get:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

MainActivity.java

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        my_method(); //WORKS WELL
    }

    public void my_method() {
        startActivity( new Intent( Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse( "package:" + getPackageName() ) ) );
    }
}

My_view.java

public void my_calling_method() { 
    try
    {
        MainActivity obj = new MainActivity ();
        obj.my_method(); // PROBLEM
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }   
}                   

Any help will be very appreciated.

Source: Android Questions

LEAVE A COMMENT