how to solve this error : 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

huangapple go评论124阅读模式
英文:

how to solve this error : 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

问题

XML 代码和 Java 代码中的注释将不被翻译,以下是翻译好的内容:

XML 代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="@drawable/wall_grad"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView_heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="208dp"
        android:text="The counter app"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView_counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="84dp"
        android:text="0"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView_heading" />

    <Button
        android:id="@+id/button_counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView_counter"
        app:layout_constraintVertical_bias="0.198" />
</androidx.constraintlayout.widget.ConstraintLayout>
Java 代码

package com.example.counter_08_01_23;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    TextView heading1, counter_text1;
    Button btn1;
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        heading1 = findViewById(R.id.textView_heading);
        counter_text1 = findViewById(R.id.textView_counter);
        btn1 = findViewById(R.id.button_counter);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 添加功能

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                counter_text1.setText(inc_counter());
            }
        });
    }

    public int inc_counter() {
        return ++counter;
    }

}

日志信息:

> E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.counter_08_01_23, PID: 22639
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.counter_08_01_23/com.example.counter_08_01_23.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3197)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3334)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2025)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:226)
        at android.app.ActivityThread.main(ActivityThread.java:7191)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.counter_08_01_23.MainActivity.onCreate(MainActivity.java:28)
        at android.app.Activity.performCreate(Activity.java:7376)
        at android.app.Activity.performCreate(Activity.java:7367)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3177)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3334)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2025)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:226)
        at android.app.ActivityThread.main(ActivityThread.java:7191)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)
I/Process: Sending signal. PID: 22639 SIG: 9

请注意,上述日志中的错误信息指出按钮对象为空,因此需要确保在 setContentView(R.layout.activity_main); 之后初始化按钮对象。

英文:

I am trying to code a counter app in which pressing the "Button" increments the counter and displays it in the TextView. I followed the exact same procedure as my online teacher. But, the code is not running.

XML code:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;@drawable/wall_grad&quot;
    tools:context=&quot;.MainActivity&quot;&gt;

    &lt;TextView
        android:id=&quot;@+id/textView_heading&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginTop=&quot;208dp&quot;
        android:text=&quot;The counter app&quot;
        android:textSize=&quot;24sp&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.497&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/textView_counter&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginTop=&quot;84dp&quot;
        android:text=&quot;0&quot;
        android:textSize=&quot;25sp&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.498&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toBottomOf=&quot;@+id/textView_heading&quot; /&gt;

    &lt;Button
        android:id=&quot;@+id/button_counter&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;Button&quot;
        android:textSize=&quot;22sp&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.498&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toBottomOf=&quot;@+id/textView_counter&quot;
        app:layout_constraintVertical_bias=&quot;0.198&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

Java Code:

package com.example.counter_08_01_23;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    TextView heading1 , counter_text1;
    Button btn1;
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        heading1 = findViewById(R.id.textView_heading);
        counter_text1 = findViewById(R.id.textView_counter);
        btn1 = findViewById(R.id.button_counter);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Adding functionality

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                counter_text1.setText(inc_counter());
            }
        });
    }

    public int inc_counter(){
        return ++counter;
    }

}

The Log is as follows :
>
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.counter_08_01_23, PID: 22639
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.counter_08_01_23/com.example.counter_08_01_23.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3197)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3334)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2025)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7191)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.counter_08_01_23.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:7376)
at android.app.Activity.performCreate(Activity.java:7367)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3177)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3334) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2025) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:226) 
at android.app.ActivityThread.main(ActivityThread.java:7191) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942) 
I/Process: Sending signal. PID: 22639 SIG: 9

答案1

得分: 2

初始化视图并设置内容

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

heading1 = findViewById(R.id.textView_heading);
counter_text1 = findViewById(R.id.textView_counter);
btn1 = findViewById(R.id.button_counter);

您可以使用视图绑定来使您的工作更加轻松
英文:

Initialise views below set content

  super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


heading1 = findViewById(R.id.textView_heading);
counter_text1 = findViewById(R.id.textView_counter);
 btn1 = findViewById(R.id.button_counter);

You can use view binding which make your work more easier

答案2

得分: 0

- 在这里,你只需要将上下的行交换一下顺序。因为你首先声明了findViewById(),然后才充气XML布局。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // 提升你的布局到Java类级别。
    setContentView(R.layout.activity_main);

    // 然后从XML中查找你的视图
    btn1 = findViewById(R.id.button_counter);
    ...
}
英文:

- Here, you need to change just the line up and down. Because you declare findViewById() first of inflating XML Layout.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // Raise your layout to Java class level.

    // Then find Your view from xml
    btn1 = findViewById(R.id.button_counter);
    ...
}

huangapple
  • 本文由 发表于 2023年1月9日 10:19:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定