由于NullPinterException而导致应用崩溃

时间:2019-04-13 10:40:50

标签: java android nullpointerexception

不幸的是,我试图启动NewEventActivity时按下浮动操作按钮会导致应用崩溃。这是我的代码:

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

我确保这两个活动都在清单中。

1 个答案:

答案 0 :(得分:4)

原因是您试图将侦听器设置为布局中没有引用的FloatingActionButton

您应该按ID查找它:

添加private FloatingActionButton mFloatingActionButton;

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);
    }
}