aze45sq6d aze45sq6d - 1 month ago 11
Java Question

Null object reference toolbar android

I am trying to make a second

Toolbar
, next to the one I have in my top bar.
Basically there is a
Button
and when this is pressed, a bar pops up in the window.
The user should be able to read something on the bar and can push a
Button
.
Right now I am trying to just get text on there. But that doesn't seem to work.

.java function: (called when some button is pushed, this shows the toolbar)

public void showDialogue() {
//Set popupscherm as view
View v = getLayoutInflater().inflate(R.layout.popupscherm,null);
AlertDialog.Builder adb = new AlertDialog.Builder(GraphActivity.this);
adb.setView(v);
// Find the toolbar view inside the activity layout
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("test"); //Here it gives the error
AlertDialog alert = adb.create();

alert.show();


popupscherm.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>

</LinearLayout>


error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(java.lang.CharSequence)' on a null object reference

Answer

Use

 View v = getLayoutInflater().inflate(R.layout.popupscherm,null);
 toolbar = (Toolbar) v.findViewById(R.id.toolbar);

instead of

toolbar = (Toolbar) findViewById(R.id.toolbar);

because view v has the popupscher.xml view otherwise with this findViewById(R.id.toolbar); you are trying to find the toolbar in the current set layout of activity which is different from popupscherm.xml