Java – NullPointerException when calling a self-writing class

NullPointerException when calling a self-writing class… here is a solution to the problem.

NullPointerException when calling a self-writing class

I’m calling from one class to another. I can set and get values when creating an object (see log), but there are many ways to throw an exception (see also log). For example, toasts. If I put the code in the original class to toast something, it works, if I try to call it, it doesn’t work. In my code below, these things that don’t work are commented out (code...).

This is Main.class:

public class Main extends Activity {
private MyMenu myMenu;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

myMenu = new MyMenu ();

myMenu.setMyMenu (3, "some text");
    int number = myMenu.getMyMenuNumber();
    String text = myMenu.getMyMenuString();

Log.d("LOG", "number is " + number + " and text is '" + text + "'.");

try {
        Log.d ("LOG", "startMain error");
        myMenu.startMain();
        startActivity(new Intent (this, Page1.class));
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

try {
        Log.d ("LOG", "putToast error");
        myMenu.putToast();
        Toast.makeText(
                this, 
                "This is a toast", 
                Toast.LENGTH_LONG)
                .show();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    try {
        Log.d ("LOG", "inflateMenu error");
        myMenu.inflateMenu(menu);
        getMenuInflater().inflate(R.menu.menu, menu);

} catch (NullPointerException e) {
        e.printStackTrace();
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    try {
        Log.d ("LOG", "isOptionsButtonClicked error");
        myMenu.isOptionsButtonClicked(item);
        switch (item.getItemId()) {     
        case R.id.feedback:
            startActivity(new Intent (this, Page1.class));
            break;
        case R.id.more_information:
            startActivity(new Intent (this, Page1.class));
            break;
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return super.onOptionsItemSelected(item);
}
}

This is MyMenu.class:

public class MyMenu extends Activity {
    int number;
    String text;

public MyMenu() {

}
public void setMyMenu (int number, String text) {
    this.number = number;
    this.text = text;
}
public int getMyMenuNumber () {
    return number;
}
public String getMyMenuString () {
    return text;
}

public void startMain () {
    startActivity(new Intent (this, Page1.class));
}

public void inflateMenu (Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
}
public void putToast () {
    Toast.makeText(
            this, 
            "This is a toast", 
            Toast.LENGTH_LONG)
    .show();
}
public void isOptionsButtonClicked (MenuItem item) {
    switch (item.getItemId()) {     
    case R.id.feedback:
        startActivity(new Intent (this, Page1.class));
        break;
    case R.id.more_information:
        startActivity(new Intent (this, Page1.class));
        break;
    }
}
}

Again, everything in running Main.class works perfectly, but calling other classes doesn’t work.

Update

This is part of the log/stack trace:

05-15 08:13:13.502: DEBUG/LOG(546): inflateMenu error
05-15 08:13:13.513: WARN/System.err(546): java.lang.NullPointerException
05-15 08:13:13.522: WARN/System.err(546):     at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
05-15 08:13:13.522: WARN/System.err(546):     at android.view.MenuInflater.inflate(MenuInflater.java:77)
05-15 08:13:13.522: WARN/System.err(546):     at com.test.MyMenu.inflateMenu(MyMenu.java:34)
05-15 08:13:13.533: WARN/System.err(546):     at com.test.Main.onCreateOptionsMenu(Main.java:52)
05-15 08:13:13.542: WARN/System.err(546):     at android.app.Activity.onCreatePanelMenu(Activity.java:2123)
05-15 08:13:13.542: WARN/System.err(546):     at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:305)
05-15 08:13:13.542: WARN/System.err(546):     at com.android.internal.policy.impl.PhoneWindow.onKeyDownPanel(PhoneWindow.java:550)
05-15 08:13:13.582: WARN/System.err(546):     at com.android.internal.policy.impl.PhoneWindow.onKeyDown(PhoneWindow.java:1192)
05-15 08:13:13.582: WARN/System.err(546):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1636)
05-15 08:13:13.582: WARN/System.err(546):     at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2368)
05-15 08:13:13.582: WARN/System.err(546):     at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2338)
05-15 08:13:13.582: WARN/System.err(546):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1641)
05-15 08:13:13.582: WARN/System.err(546):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-15 08:13:13.592: WARN/System.err(546):     at android.os.Looper.loop(Looper.java:123)
05-15 08:13:13.592: WARN/System.err(546):     at android.app.ActivityThread.main(ActivityThread.java:4363)
05-15 08:13:13.602: WARN/System.err(546):     at     java.lang.reflect.Method.invokeNative(Native Method)
05-15 08:13:13.602: WARN/System.err(546):     at java.lang.reflect.Method.invoke(Method.java:521)
05-15 08:13:13.602: WARN/System.err(546):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-15 08:13:13.602: WARN/System.err(546):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-15 08:13:13.602: WARN/System.err(546):     at dalvik.system.NativeStart.main(Native Method)

And:

05-15 08:13:03.592: DEBUG/LOG(546): putToast error
05-15 08:13:03.612: WARN/System.err(546): java.lang.NullPointerException
05-15 08:13:03.621: WARN/System.err(546):     at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
05-15 08:13:03.633: WARN/System.err(546):     at android.widget.Toast.<init>(Toast.java:89)
05-15 08:13:03.633: WARN/System.err(546):     at android.widget.Toast.makeText(Toast.java:231)
05-15 08:13:03.633: WARN/System.err(546):     at com.test.MyMenu.putToast(MyMenu.java:37)
05-15 08:13:03.641: WARN/System.err(546):     at com.test.Main.onCreate(Main.java:37)
05-15 08:13:03.641: WARN/System.err(546):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-15 08:13:03.652: WARN/System.err(546):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
05-15 08:13:03.652: WARN/System.err(546):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-15 08:13:03.652: WARN/System.err(546):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-15 08:13:03.661: WARN/System.err(546):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-15 08:13:03.661: WARN/System.err(546):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-15 08:13:03.671: WARN/System.err(546):     at    android.os.Looper.loop(Looper.java:123)
05-15 08:13:03.671: WARN/System.err(546):     at android.app.ActivityThread.main(ActivityThread.java:4363)
05-15 08:13:03.671: WARN/System.err(546):     at java.lang.reflect.Method.invokeNative(Native Method)
05-15 08:13:03.683: WARN/System.err(546):     at java.lang.reflect.Method.invoke(Method.java:521)
05-15 08:13:03.683: WARN/System.err(546):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-15 08:13:03.691: WARN/System.err(546):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-15 08:13:03.691: WARN/System.err(546):     at dalvik.system.NativeStart.main(Native Method)

Hope this helps!

Update 2

This is the Page1 .class of the request. But when I don’t use MyMenu.class, everything works fine again.

public class Page1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page1);
}

}

In addition, you can download Android projects from Microsoft/Windows Live Skydrive:
http://cid-f45ce92851885387.office.live.com/browse.aspx/Stackoverflow

Solution

I don’t understand why you would delegate this method below to another activity:

public void startMain () {
   startActivity(new Intent (this, Page1.class));  this <- here is problem
}

I think that’s because the design is bad. Don’t do that. Use intents. Pass data between activities in the bundle’s intent.
In your case, you did not pass the Context to the MyMenu activity. MyMenu doesn’t have an Application Context instance, so you encounter an NPE.

Comment Reply:
Of course, you can use the static startMain method. But notice what ‘this’ in new Intent(this, Page1.class) is. You should pass the activity context from which the new activity was started.

public static void startMain (Activity context) {
   context.startActivity(new Intent (context, Page1.class));
}

Related Problems and Solutions