-3

My Activity class looks like that:

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

}

My activity_fullscreen.xml file looks like that:

<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>

Now I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
Do you know how to fix the null pointer exception? I don't know why my button is null.
Is it right how I initialize the button or is the error caused by findViewById?

mafioso
  • 1,630
  • 4
  • 25
  • 45

2 Answers2

0

Replace

  private Button btnTakePhoto = new Button(this);

by

private Button btnTakePhoto;
Ganesh Pokale
  • 1,538
  • 1
  • 14
  • 28
0

You you can't set you buttons to new Button(this). It will likely always be null, if not incorrect. I would define your button in the onCreate method only, then set it to the necessary id.

To answer your question specifically, the findViewById part of your code is correct. You just messed up the definition of your Button variables

Will Evers
  • 934
  • 9
  • 17