0

I'm trying to make an Intent to start the NewEventActivityunfortunately the app crashejn when the floating action button is pressed. Here is my code:

MainActivity:

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

            }
            public void newEventIntent(View v){
                Intent intent = new Intent(this, NewEventActivity.class);
                startActivity(intent);
        }
    }

activity_main.xml:

        <android.support.design.widget.FloatingActionButton
        android:onClick="newEventIntent"
        android:id="@+id/add_event_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="20dp"
        android:src="@drawable/baseline_add_24"/>

LogCat:

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

I made sure that both activities are in the manifests.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Moritz L.
  • 177
  • 1
  • 2
  • 10

1 Answers1

4

The reason is that you are trying to set a listener to a FloatingActionButton that it does not have reference in your layout.

You should find it by id :

Add private FloatingActionButton mFloatingActionButton;

and

floatingActionButton=findViewById(R.id.add_event_fab);

public class MainActivity extends AppCompatActivity {

    private FloatingActionButton mFloatingActionButton;

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

    floatingActionButton=findViewById(R.id.add_event_fab);

        }
        public void newEventIntent(View v){
            Intent intent = new Intent(this, NewEventActivity.class);
            startActivity(intent);
    }
}
milad salimi
  • 1,580
  • 2
  • 12
  • 31