Home > Software engineering >  I'm getting this error: Attempt to invoke virtual method 'android.view.View android.widget
I'm getting this error: Attempt to invoke virtual method 'android.view.View android.widget

Time:08-18

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:

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

CodePudding user response:

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!

  • Related