Home > Enterprise >  Android studio error when setting visibility
Android studio error when setting visibility

Time:01-01

This error keeps appearing even though I am pretty sure I referenced the correct View/toolbar.

Attempt to invoke virtual method 'void androidx.appcompat.widget.Toolbar.setVisibility(int)' on a null object reference

My goals is to build a fragment which has a different toolbar then the MainActivity, I did not set any of the toolbars as an Actionbar as there is no need for it.

MainActivity XML

<include layout="@layout/custom_toolbar"
    android:id="@ id/customToolbarInclude"
    ></include>

<include layout="@layout/second_toolbar"
    android:id="@ id/secondLayoutInclude"
   ></include>

Activity Toolbar XML

<com.google.android.material.appbar.AppBarLayout
    android:id="@ id/toolbarcover"
    android:layout_width="match_parent"
    android:background="@color/black"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:visibility="visible"
        android:id="@ id/MenuToolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        style="@style/MyToolbar"
        android:fitsSystemWindows="true"
        app:titleCentered="true"
        android:elevation="30dp">
       ...
    </com.google.android.material.appbar.MaterialToolbar>

The unique toolbar

<com.google.android.material.appbar.MaterialToolbar
        android:id="@ id/topAppBarthesecond"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:visibility="gone"
        style="@style/MyToolbar"
        android:fitsSystemWindows="true"
        app:titleCentered="true"
        android:elevation="30dp">
        
    </com.google.android.material.appbar.MaterialToolbar>

The Fragment I tried to switch the toolbar

val mainToolbar = view.findViewById<Toolbar>(R.id.MenuToolBar)
val SecondaryToolBar = view.findViewById<Toolbar>(R.id.topAppBarthesecond)

    mainToolbar.visibility = View.GONE
    SecondaryToolBar.visibility = View.VISIBLE

Specifically the error mentioned above occurs at the line mainToolbar.visibility = View.GONE, which I do not understand, I am referencing the toolbar how is it null? It works perfectly fine when I do it in XML

CodePudding user response:

The first thing you should always check is which one is null, the view or the mainToolbar?

  • If the mainToolbar is null while the view isn't, you probably do something wrong when inflating the view.

  • If the view is null, the most probable cause is that the code snippet you posted is being executed before the view has successfully been inflated; for example, it's written in the onCreate(..) and not in the onViewCreated(..).

Be sure you respect the view's lifecycle when doing any view operation.

enter image description here

  • Related