-2

I'm trying to define a button in my Home activity to open my Settings activity but I get the error :

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.padmw/com.example.padmw.Home}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

My layout for the Settings item is in res/menu, I tried moving it to res/layout but then it says that element item should not be there. What should i do?

My Button in Home.class:

    Button mButton = (Button) findViewById(R.id.action_settings);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Home.this, SettingsActivity.class));
        }
    });

My item in res/home.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>
Naveen
  • 1,441
  • 2
  • 16
  • 41
Chris911
  • 909
  • 1
  • 6
  • 10

2 Answers2

1

If you want to use findViewById, button should be in your layout, not menu.

For menu you need to override onOptionsItemSelected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // do something
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

And you need to inflate home.xml menu :

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

Note that your home.xml should be in res/menu/ folder.

Ali
  • 9,800
  • 19
  • 72
  • 152
1

So for the menu item, we do in this way 1) To specify the options menu for an activity, override onCreateOptionsMenu(). In this method, you can inflate your menu resource:-

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

2)Handling click events: You can match this ID against known menu items to perform the appropriate action. For example:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_settings:
          // do your work
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}
Manoj Kumar
  • 332
  • 1
  • 7