0

Error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kritisharan.tictactoe/com.example.kritisharan.tictactoe.starter_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Code in MainActivity:

public class MainActivity extends AppCompatActivity {

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

    FloatingActionButton reset = (FloatingActionButton) findViewById(R.id.reset);

    reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this, MainActivity.class));
        }
    });
}

XML Code in activity_main.xml

<include layout="@layout/content_main"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/reset"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="10sp"
    android:src="@android:drawable/ic_menu_revert"/>

Don't know why it is considering a null reference. Searched all the solutions but couldn't find anything that works. Please help.

HassanUsman
  • 1,485
  • 1
  • 17
  • 34
Kriti Sharan
  • 231
  • 3
  • 9

3 Answers3

2

Change this line of code:

setContentView(R.layout.content_main);

to: setContentView(R.layout.activity_main);

Android Geek
  • 7,328
  • 2
  • 17
  • 32
1

Change your OnCreate() method with this one.

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

.......

}

Try this.

HassanUsman
  • 1,485
  • 1
  • 17
  • 34
1

The content_main.xml you're inflating does not contain a view with id reset as you're trying to find in onCreate(). Perhaps you are inflating the wrong XML layout. It looks like you want activity_main.xml instead.

Doug Stevenson
  • 236,239
  • 27
  • 275
  • 302