简体   繁体   中英

Java null pointer exception on TextView.setText()

I got a problem on my code. I work on Android Studio and when I launch my code I get this error :

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

I search on a lot of web site and I can't find any responses.

Here is my code :

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

The error appear in onCreate method at nbDef.setText line.

Here is the XML file : 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>

The failing TextView is the last one with "number" as id.

Well I know what is a NullPointerException but I don't understand why it's failing because a do the exact same operations with the printPlayer TextView and it not fail.

Thanks a lot for the help you can give me !

I think here you are getting NPE

nbDef = findViewById(R.id.number);

The only reason for findViewById to return null if you are passing a valid id is that you are either setting the wrong content view (with setContentView)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM