- java.lang.NullPointerException - setText on null object reference

2022-09-01 10:36:01

这就是我几个小时试图做的事情:我有一个MainActivity.java文件(下面列出)和一个带有开始按钮的fragment_start.xml文件。点击开始按钮应显示带有点/舍入和倒计时文本视图的activity_main.xml文件。它不起作用,这就是正在发生的事情:

logcat 告诉我: PID: 1240 java.lang.NullPointerException: 尝试在 null 对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)'

模拟器显示:不幸的是,GAME 已停止。

有必要提到我在编程方面相当新吗?

感谢您的任何建议!

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class MainActivity extends Activity implements View.OnClickListener {

private int points;
private int round;
private int countdown;

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

private void newGame () {
    points=0;
    round=1;
    initRound();
}

private void initRound() {
    countdown = 10;
    update();
}

private void update () {
    fillTextView(R.id.points, Integer.toString(points));
    fillTextView(R.id.round, Integer.toString(round));
    fillTextView(R.id.countdown, Integer.toString(countdown * 1000));
}

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text);
}

private void showStartFragment() {
    ViewGroup container = (ViewGroup) findViewById(R.id.container);
    container.removeAllViews();
    container.addView(
            getLayoutInflater().inflate(R.layout.fragment_start, null) );
    container.findViewById(R.id.start).setOnClickListener(this);
}

@Override
public void onClick(View view) {
    if(view.getId() == R.id.start) {
        startGame();
    }
}

public void startGame() {
    newGame();
}
}

答案 1

问题是 .变量 tv 可能是,并且您调用该方法,但您不能。我猜问题出在方法上,但它不在这里,所以我不能说更多,没有代码。tv.setText(text)nullsetTextnullfindViewById


答案 2

这就是你的问题所在:

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text); // tv is null
}

--> (TextView) findViewById(id);返回 null 但是从您的代码中,我找不到此方法返回 null 的原因。尝试跟踪,您作为参数提供的id以及是否存在具有指定id的视图。

错误消息非常清楚,甚至告诉您使用哪种方法。从文档中:

public final View findViewById (int id)
    Look for a child view with the given id. If this view has the given id, return this view.
    Parameters
        id  The id to search for.
    Returns
        The view that has the given id in the hierarchy or null

http://developer.android.com/reference/android/view/View.html#findViewById%28int%29

换句话说:您没有将 id 作为参数的视图。


推荐