-java.lang.NullPointerException-空对象引用上的setText [英] - java.lang.NullPointerException - setText on null object reference

查看:99
本文介绍了-java.lang.NullPointerException-空对象引用上的setText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is what I'm trying to do for several hours: I've got a MainActivity.java file (listing below) and a fragment_start.xml file with a start button. Tapping the start-button should display the activity_main.xml file with points-/round- and countdown-Textviews. It doesn't work and this is what is happening:

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

The logcat tells me: PID: 1240 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

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

有必要提一下我是编程新手吗?

Necessary to mention that I'm rather new in programming?

感谢您的任何建议!

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();
}
}

推荐答案

问题是 tv.setText(text).变量tv可能是 null ,您可以在该 null 上调用 setText 方法,但不能.我的猜测是问题出在 findViewById 方法上,但是它不在这里,所以如果没有代码,我就无法告诉更多信息.

The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't. My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.

这篇关于-java.lang.NullPointerException-空对象引用上的setText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆