BlackORTS
BlackORTS

Reputation: 23

android studio says that im trying to link an id to null

this is debug message:

Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference at com.example.app.CalculatorActivity.onCreate(CalculatorActivity.java:22)

and here's the code:

package com.example.app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class CalculatorActivity extends AppCompatActivity {

    private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0;
    private Button btnPlus, btnMinus, btnMultiply, btnDivide, btnClear, btnResult;
    private TextView textResult;

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

        btn1 = btn1.findViewById(R.id.btn_1);
        btn2 = btn2.findViewById(R.id.btn_2);
        btn3 = btn3.findViewById(R.id.btn_3);
        btn4 = btn4.findViewById(R.id.btn_4);
        btn5 = btn5.findViewById(R.id.btn_5);
        btn6 = btn6.findViewById(R.id.btn_6);
        btn7 = btn7.findViewById(R.id.btn_7);
        btn8 = btn8.findViewById(R.id.btn_8);
        btn9 = btn9.findViewById(R.id.btn_9);
        btn0 = btn0.findViewById(R.id.btn_0);

        btnPlus = btnPlus.findViewById(R.id.btn_plu);
        btnMinus = btnMinus.findViewById(R.id.btn_min);
        btnMultiply = btnMultiply.findViewById(R.id.btn_mul);
        btnDivide = btnDivide.findViewById(R.id.btn_div);
        btnClear = btnClear.findViewById(R.id.btn_clr);
        btnResult = btnResult.findViewById(R.id.btn_equ);

        textResult = textResult.findViewById(R.id.txt_result);

    }

    public void numberOperation(@NonNull View v){

        Button button;

        button = (Button)v;

        String buttonText = button.getText().toString();

        textResult.setText(textResult.getText().toString()+buttonText);

    }

}

i checked if in my xml if i miss spelled the id or something but all is perfect, please help

Upvotes: 1

Views: 184

Answers (1)

Philipp K.
Philipp K.

Reputation: 26

You cannot call Button.findViewById(int id); like you have done here:

btn1 = btn1.findViewById(R.id.btn_1);

instead you should call it directly from the Activity like:

btn1 = findViewById(R.id.btn_1);

Upvotes: 1

Related Questions