Android - How to Handle Null Case for ViewStubs

20 Views Asked by At

I'm a self taught Android developer, I want to use a ViewStub in my (live) app, but I'm not sure what to do in the null case.

My XML - you_win_overlay.xml:

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/stub"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <TextView
            android:id="@+id/title"
            style="@style/title_style"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

My Main Activity XML

<ViewStub
            android:id="@+id/you_win_stub"
            android:inflatedId="@+id/you_win_stub_inflated"
            android:layout="@layout/you_win_overlay"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent">
</ViewStub>

In my Main Activity I call a method that uses the ViewStub to show the player the win game display. So the method looks like so:

showTheEndGameOverlay(SharedPreferences memory, ViewStub viewStub, Animation slide) {

     View inflated;

     if(viewStub != null) {
   
          inflated = viewStub.inflate();
          inflated.setZ(12);

          TextView theTitle = (TextView) inflated.findViewById(R.id.title);
          theTitle.setText(memory.getString("currentTitle", "Default Title"));

     } else {

         WHAT WOULD I DO HERE???
         WHAT WOULD I DO HERE???
         WHAT WOULD I DO HERE???

    }
}

I'm not sure what to do here for the null case. I copied this code from a couple of examples, and in each one they test for viewStub != null. In testing the code in my game it works perfectly OK, each time the viewStub is not null and everything executes as expected. Every time I test, I win a game and the "showTheEndGameOverlay" method executes the viewStub is not null. So I'm not sure I even need to do this null check, the viewStub will always be in the Main Activity's XML file...so how could be ever be null?.

However, since this is new to me, I don't want to make a mistake and overlook handling a null case if I need to. Can anyone assist? Thanks.

0

There are 0 best solutions below