joe martin
joe martin

Reputation: 93

Use a button in the action bar with an intent to start a new activity

I've got buttons in my action bar like so:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- Search, should appear as action button -->
<item android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    android:title="@string/action_search"
    app:showAsAction="ifRoom"
    android:onClick="doubleBet"/>
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_settings"
    android:title="@string/action_settings"
    app:showAsAction="never" />

I've added an onClick to the action_search, to launch a new activity. Here is my Java to launch the activity.

public void doubleBet(View view){
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    String x = "Hello";
    intent.putExtra("key", x); //Optional parameters
    startActivity(intent);

}

I then receive the intent like so, in my DisplayMessageActivity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    String message = intent.getStringExtra("key");
}

However, the app crashes when I run it. What could be the cause of this?

Here is the logcat:

https://gist.github.com/anonymous/862e5e33a10c23d3bbc9

Upvotes: 1

Views: 918

Answers (1)

Mauker
Mauker

Reputation: 11487

Try changing your doubleBet method from this:

public void doubleBet(View view){
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    String x = "Hello";
    intent.putExtra("key", x); //Optional parameters
    startActivity(intent);
}

to this:

public boolean doubleBet(MenuItem view){
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    String x = "Hello";
    intent.putExtra("key", x); //Optional parameters
    startActivity(intent);
    return true;
}

Upvotes: 3

Related Questions