FAB + Nullpointerexception button

Asked

Viewed 167 times

0

I suppose it’s a simple problem, but I can’t visualize the solution. I created a floating button (FAB) in a Fragment on Android, and when trying to configure Clicklistener, I get a Nullpointer error. Follow the codes:

xml:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right|end"
        android:layout_margin="16dp"
        android:clickable="true"/>

Mainactivity.java

FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Intent criar = new Intent(MainActivity.this, Fragment1.class);
         startActivity(criar);
     }
}

The error message says that the code tries to call the method setOnClickListener in a null object.

Any hint is welcome. I appreciate.

  • You get NullPointerException, for the floatingActionButton is null. The XML it is declared refers to your MainActivity?

  • Yes. But why is null? findViewById should not be the required assignment?

1 answer

0

I’ve just found in your question that you stated the FloatingActionButton in your Fragment. This way you cannot use findViewById() directly from your MainActivity, and that’s the reason he’s getting null.

Look at the documentation:

Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

That is, using the findViewById() straight from her MainActivity, the function will look for this FloatingActionButton within the layout that is connected to your MainActivity and not of your Fragment.

To solve the problem just you instantiate this FloatingActionButton within your Fragment and set your event to click inside, or you move that FloatingActionButton for the layout of your MainActivity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.