TextView.setText()

时间:2019-02-28 10:32:29

标签: java nullpointerexception textview

我的代码有问题。 我在Android Studio上工作,当我启动代码时,出现此错误:

  

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

我在很多网站上搜索,但找不到任何答复。

这是我的代码:

我的活动Action.java:

public class Action extends AppCompatActivity {
    private TextView nbDef;
    private TextView printPlayer;
    private final List<String> name = new Vector<>();
    private final HashMap<String, Integer> score = new HashMap<>();
    private String mode;
    private int nbAllTurn;
    private String TurnPlayer;
    private int nbTurn = 0;
    private int idPlayer = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_action);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        nbDef = findViewById(R.id.number);
        printPlayer = findViewById(R.id.challenge);

        nbDef.setText("0/" + nbAllTurn);

        Intent intent = getIntent();
        mode = intent.getStringExtra("mode");
        nbAllTurn = intent.getIntExtra("nbTurn", -1);
        String player = intent.getStringExtra("players");

        String[] rawPlayers = player.split("\n");

        for (String rawPlayer : rawPlayers) {
            name.add(rawPlayer);
            score.put(rawPlayer, 0);
        }
        DoAction();
    }

    private void DoAction() {
        List<String> OtherPlayers = new Vector<>();

        TurnPlayer = name.get(idPlayer);
        for (int index = 0; index < name.size(); index++) {
            if (!name.get(index).equals(TurnPlayer))
                OtherPlayers.add(name.get(index));
        }
        printPlayer.setText(TurnPlayer);

        List<String> challenges = new ArrayList<>();

        challenges.add(", raconte une anecdote gênante sur ");
        challenges.add(", fais un chifoumi avec ");
        challenges.add(", raconte une histoire chiante sur  ");
        challenges.add(", mange des chaussettes avec ");

        String choosePlayer = OtherPlayers.get(new Random().nextInt(OtherPlayers.size()));
        String chooseChallenge = challenges.get(new Random().nextInt(challenges.size()));
        String playerAction = printPlayer.getText().toString() + chooseChallenge;
        printPlayer.setText(playerAction);
        String playersAction = printPlayer.getText().toString() + choosePlayer;
        printPlayer.setText(playersAction);

        String challengeNum = Integer.toString(nbTurn) + "/" + Integer.toString(nbAllTurn);

        nbDef.setText(challengeNum);

        idPlayer += 1;

        if (idPlayer == name.size()) {
            idPlayer = 0;
        }

        nbTurn +=1;

        if (nbTurn == nbAllTurn) {
            StringBuilder builder = new StringBuilder();

            for (String name : score.keySet()) {
                builder.append(name).append(" : ").append(score.get(name)).append("\n");
            }

            Intent intent = new Intent(this, ScoreBoard.class);
            intent.putExtra("datas", builder.toString());
            startActivity(intent);

            finish();
        }
    }

    public void successClick(View v) {
        DoAction();

        score.put(TurnPlayer, score.get(TurnPlayer) + 1);
    }

    public void failClick(View v) {
        DoAction();
    }
}

错误出现在nbDef.setText行的onCreate方法中。

这是XML文件:activity_action.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/body_action_back"
    tools:context=".Action"
    tools:layout_editor_absoluteY="25dp">

<TextView
        android:id="@+id/challenge"
        android:layout_width="0dp"
        android:layout_height="127dp"
        android:layout_marginEnd="56dp"
        android:textAlignment="center"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.373"
        tools:maxLines="5" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="172dp"
        android:layout_marginStart="69dp"
        android:contentDescription="@string/cartoon"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/challenge"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.334"
        app:srcCompat="@drawable/pikachu" />

    <!--<RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="11dp"
        app:layout_constraintEnd_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </RelativeLayout>-->

    <ImageButton
        android:id="@+id/success_button"
        android:layout_width="186dp"
        android:layout_height="68dp"
        android:layout_marginStart="144dp"
        android:layout_marginTop="53dp"
        android:layout_marginEnd="59dp"
        android:layout_marginBottom="38dp"
        android:onClick="successClick"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/fail_button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@drawable/successbutton" />

    <ImageButton
        android:id="@+id/fail_button"
        android:layout_width="186dp"
        android:layout_height="68dp"
        android:layout_marginStart="59dp"
        android:layout_marginTop="72dp"
        android:layout_marginEnd="156dp"
        android:layout_marginBottom="38dp"
        android:onClick="failClick"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/success_button"
        app:layout_constraintTop_toBottomOf="@+id/challenge"
        app:srcCompat="@drawable/failbutton" />

    <TextView
        android:id="@+id/number"
        android:layout_width="88dp"
        android:layout_height="53dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="119dp"
        android:layout_marginEnd="7dp"
        android:layout_marginBottom="7dp"
        android:textAlignment="center"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/fail_button"
        app:layout_constraintTop_toBottomOf="@+id/challenge"
        tools:maxLines="5"/>
</android.support.constraint.ConstraintLayout>

失败的TextView是最后一个以id为ID的数字。

我知道什么是NullPointerException,但我不明白为什么它会失败,因为a使用printPlayer TextView进行了完全相同的操作,并且没有失败。

非常感谢您能给我的帮助!

1 个答案:

答案 0 :(得分:0)

我认为您正在获得NPE

nbDef = findViewById(R.id.number);

如果传递有效的id,则findViewById返回null的唯一原因是您设置了错误的内容视图(使用setContentView)