0

Recently, my onCreate() method has been having a hard time connecting a Toolbar to a toolbar in my xml file.

Code:

 super.onCreate(savedInstanceState);
 setContentView(R.layout.content_two_player_game);
 Toolbar toolbar = (Toolbar) findViewById(R.id.two_player_toolbar);
 setSupportActionBar(toolbar);

The app compiles and runs in the main screen and the single player screen, but when I try and start the two player screen, it crashes. The ID is correct and yet the toolbar is still Null when I try setSupportActionBar(toolbar).

My error:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.phoenixdev.yahtzee/com.***.***.TwoPlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference

The activity_two_player_game.xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.phoenixdev.yahtzee.TwoPlayerActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/two_player_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_two_player_game" />

</android.support.design.widget.CoordinatorLayout>
Karakuri
  • 38,365
  • 12
  • 84
  • 104
TheAnonymous010
  • 725
  • 7
  • 19

3 Answers3

1

Hi did you included your toolbar on your mainActivity xml layout? Like the code below:

<include
    android:id="@+id/toolbar"
    layout="@layout/tool_bar"
    />
Diego Mello
  • 231
  • 2
  • 6
0

Change

setContentView(R.layout.content_two_player_game);

to

setContentView(R.layout.activity_two_player_game);

I presume content_two_player_game.xml does not contain the Toolbar.

Karakuri
  • 38,365
  • 12
  • 84
  • 104
0

I had a same problem and I solved it by adding this theme to my activity declaration in AndroidManifest.xml:

android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar"

like this:

<activity
    android:name=".YourActivityName"
    android:screenOrientation="portrait"
    android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar" />
Jalal Aghazadeh
  • 164
  • 4
  • 18