3

I have a UI with multiple views that show sets of buttons to the user. I use a viewflipper to manage flipping back and forth between the button sets. Recently a new error message in Android Studio showed up:

"Method invocation 'viewflipper.getDisplayedChild()' may produce 'java.lang.NullPointerException'..."

The error shows on ** **line in the Activity file:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cardviewinput);

    viewflipper = (ViewFlipper) findViewById(R.id.viewFlipper1);

   **if (viewflipper.getDisplayedChild() == 0)**
        viewflipper.setDisplayedChild(1);
        viewflipper.setDisplayedChild(viewflipper.indexOfChild(findViewById(R.id.cardviewNobuttons)));

"cardviewNobuttons" is the default layout I want to show.

In cardviewinput.xml file:

...
<LinearLayout
    android:id="@+id/LinearLayout3"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center_vertical"  >

    <ViewFlipper
    android:id="@+id/viewFlipper1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/cardview_nobuttons"
        android:id="@+id/cardviewNobuttons"  />

    <include layout="@layout/cardview_previewbuttons"
        android:id="@+id/cardviewPreviewbuttons" />

    <include layout="@layout/cardview_twobuttons"
        android:id="@+id/cardviewTwobuttons"  />

    </ViewFlipper>

</LinearLayout>

The warning in the above layout file is "The ViewFlipper layout or its LinearLayout parent is possibly useless..."

Is there a way to improve the code and negate the error messages/warnings?

AJW
  • 1,578
  • 3
  • 36
  • 77
  • 1
    Please post the entire class, or at minimum show the entire method where you initialize `viewflipper` and the entire method for your code snippet shown above. We cannot tell you how to improve code that we cannot see. – CommonsWare Apr 28 '16 at 22:12
  • 1
    Ok, understood. Will add. – AJW Apr 28 '16 at 22:13
  • 1
    Do you have different versions of this layout file in different resource sets (e.g., `res/layout/` and `res/layout-land.` or `res/layout-w800dp/`)? "The warning in the above layout file" -- that is because you have only one child of the `LinearLayout`. – CommonsWare Apr 28 '16 at 22:23
  • 1
    No I don't have different versions. – AJW Apr 28 '16 at 22:24
  • 1
    Then I am not sure why Android Studio is complaining. It does not complain in general about `findViewById()` possibly returning `null`, and I do not see what is special about your situation that would cause Android Studio to worry here. – CommonsWare Apr 28 '16 at 22:25
  • I added code from the xml layout above. I'm not sure if the error message in the layout file is a separate warning or related to the warning for the Activity file. – AJW Apr 28 '16 at 22:27

0 Answers0