如何使用OnClickListener()解决崩溃错误?

时间:2019-04-09 11:06:59

标签: android nullpointerexception

我试图添加一个点击监听器,当我添加行button1.setOnClickListener(this);我的应用程序将不再运行

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

    BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
    bottomNav.setOnNavigationItemSelectedListener(navListener);

    Button button1 = findViewById(R.id.jobs_button);
    button1.setOnClickListener(this);

    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
            new HomeFragment()).commit();
}

private BottomNavigationView.OnNavigationItemSelectedListener navListener =
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;

                switch (item.getItemId())
                {
                    case R.id.navHome:
                        selectedFragment = new HomeFragment();
                        break;
                    case R.id.navFavourites:
                        selectedFragment = new FavouritesFragment();
                        break;
                    case R.id.navSearch:
                        selectedFragment = new SearchFragment();
                        break;
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();
                return true;
            }
        };
@Override
public void onClick(View v) {
    switch(v.getId())
    {
        case R.id.jobs_button:
            Toast.makeText(this, "button clicked",Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
    }
  }
}

这是我的崩溃报告

2019-04-09 12:23:54.390 9106-9106/com.example.jobsthatcare E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.jobsthatcare, PID: 9106
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jobsthatcare/com.example.jobsthatcare.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.jobsthatcare.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)

这是我的家庭片段XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home Fragment"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        />

    <Button
        android:id="@+id/jobs_button"
        android:layout_width="200sp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200sp"
        android:text="Jobs"
        android:background="@android:color/holo_orange_dark"/>

这是主要活动的xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"
        />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_navigation"
        android:background="@color/colorAccent"
    />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

这仅仅是因为您试图将活动内的按钮绑定到:

setContentView(R.layout.activity_main);

...
Button button1 = findViewById(R.id.jobs_button);

,但是按钮不在activity_main布局内。它位于您的家庭片段布局中。