Home > Mobile >  Cannot find the element by Id in the mainActivityJava
Cannot find the element by Id in the mainActivityJava

Time:11-09

I want to select the button element by ID, but when I run the program, I get the app keeps stopping error. I ran the program in debug mode and the error Caused by:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference

Even when I click on R.id.button, the button element is displayed in the xml file.

mainActivityFile :

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity6 extends AppCompatActivity {

    private Button btn;
     private TextView txt;

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

        btn.findViewById(R.id.button);
        txt.findViewById(R.id.txt);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txt.setText("This is a new text.");
            }
        });


       // Toast.makeText(this, "str", Toast.LENGTH_LONG).show();
    }
}

xml file :

<?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"
    android:orientation="vertical"
    tools:context=".MainActivity6">

    <TextView
        android:id="@ id/txt"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:autoSizeTextType="uniform"
        android:autoSizeMinTextSize="25sp"
        android:autoSizeMaxTextSize="100dp"
        android:autoSizeStepGranularity="2sp"
        android:layout_height="wrap_content" />

    <Button
        android:id="@ id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>

CodePudding user response:

btn.findViewById(R.id.button);

You're not supposed to use it this way because btn is null at this point. You have to do the following:

btn = (Button)findViewById(R.id.button);
  • Related