Attempt to invoke virtual method on a null object

Fermé
kwinchi - Modifié le 25 août 2018 à 14:58
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 - 27 août 2018 à 11:05
Bonjour,
je reçois cet beug quand j'entre dans l'activité "topscore"

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface, int)' on a null object reference
at com.app.flier.menu.TopRankFrame.onCreate(TopRankFrame.java:50)


voici le code


package com.app.copter.menu;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.app.copter.R;
import com.app.copter.data.RankScore;
import com.app.copter.data.Storage;

public class TopRankFrame
extends Activity {
    RankScore rankScore;
    TextView[] tvNames = new TextView[5];
    TextView[] tvScores = new TextView[5];


    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.requestWindowFeature(1);
        this.getWindow().addFlags(1024);
        this.setContentView(R.layout.toprank);
        this.rankScore = Storage.loadScore((Context)this);
        Typeface typeface = Typeface.createFromAsset((AssetManager)this.getAssets(), (String)"fonts/Bradley Hand ITC.TTF");
        int n = 0;
        while (n < 5) {
            this.tvScores[n] = (TextView)this.findViewById(2131296362 + n * 2);
            this.tvNames[n] = (TextView)this.findViewById(2131296361 + n * 2);
            this.tvScores[n].setTypeface(typeface, 1);
            this.tvNames[n].setTypeface(typeface, 1);
            TextView textView = this.tvScores[n];
            Object[] arrobject = new Object[]{this.rankScore.getScore(n)};
            textView.setText((CharSequence)String.format((String)"%06d", (Object[])arrobject));
            this.tvNames[n].setText((CharSequence)this.rankScore.getName(n));

            ++n;
        }
        return;
    }

    public void toMenu(View view) {
        this.finish();
    }
}



je comprend que les variables tvscores et tvnames sont null mais je les initiés


je vous en pris de me proposer une solution


A voir également:

1 réponse

BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 3 895
27 août 2018 à 11:05
Hello,

Houla...plusieurs choses ne vont pas ici :
- évites les
this
envahissant qui ne sont pas forcément utiles
-
this.tvScores[n] = (TextView)this.findViewById(2131296362 + n * 2);
: ça, on ne le fait jamais ! Il faut toujours passer par l'ID,
R.id.xxx
car ce n'est pas toi qui force l'ID, c'est le système
- trop de cast tue le cast. Tu n'as pas forcément besoin de tout le temps caster tes paramètres
0