Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm getting this error: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference

I’m new to java and android and i’m getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.View android.widget.Button.findViewById(int)’ on a null object reference

here is my MainActivity.java code:

    package com.example.intentpassingoneactivitytoanother;
    import androidx.appcompat.app.AppCompatActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    public class MainActivity extends AppCompatActivity {
       Button button;
        @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
          button.findViewById(R.id.btn);
      button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
       // Toast.makeText(MainActivity.this, "This is toast", Toast.LENGTH_SHORT).show();
    }
    });
    }
    }

here is my activity_main.xml code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
    tools:context=".MainActivity">
    <Button
      android:id="@+id/btn"
      android:layout_gravity="center"
      android:layout_marginHorizontal="120dp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="NextButton"/>
    </LinearLayout>

>Solution :

You are trying to access the button without initialising it.

button.findViewById(R.id.btn)
should be
button = findViewById(R.id.btn)

button is null before invoking findViewById and so the exception says trying to invoke findViewById on null reference object.

Hope it helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading