由按钮引起的Android中的空指针异常

时间:2016-10-24 15:38:15

标签: android

我的Activity类看起来像这样:

public class FullscreenActivity extends AppCompatActivity {
    private Button btnTakePhoto = new Button(this);
    private Button btnRecordVideo = new Button(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fullscreen);

        btnTakePhoto = (Button) findViewById(R.id.btnTakePhoto);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                helloWorldKamera();
            }
        });
    }

    public void helloWorldKamera() {
        System.out.println("Kamera");
    }

}

我的activity_fullscreen.xml文件看起来像这样:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:text="Foto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:id="@+id/btnTakePhoto" />

        <Button
            android:text="Video"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:id="@+id/btnRecordVideo"
            />
    </LinearLayout>
</FrameLayout>

现在我收到以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
你知道如何修复空指针异常吗?我不知道为什么我的按钮为空。
我是如何初始化按钮的,还是由findViewById引起的错误?

2 个答案:

答案 0 :(得分:0)

替换

  private Button btnTakePhoto = new Button(this);

通过

private Button btnTakePhoto;

答案 1 :(得分:0)

您无法将按钮设置为新按钮(此)。如果不是错误的话,它可能总是为空。我只会在onCreate方法中定义你的按钮,然后将其设置为必要的id。

要具体回答您的问题,您的代码的findViewById部分是正确的。你刚搞砸了Button变量的定义

相关问题