-4

I am using LibGDX to build a game for android. I am getting a null pointer exception in this class but I dont know why (check the comments).

public class ScoreFont {
    private Texture _numbers[];
    private int _number;

    public ScoreFont(){
       //Load font
       for(int i = 0; i <= 9; i++){
            _numbers = new Texture[10];
            _numbers[i] = new Texture("font_"+i+".png");
           /*the line above works fine. if I use if(_number[i] != null) System.out.println("loaded"); it will print*/

        }
        _number = 0;
    }

    public void setNumber(int number){
        _number = number;
    }

    public void draw(SpriteBatch sb, float x, float y, float width, float height){
        String numberString = Integer.toString(_number);

        int numDigits = numberString.length();
        float totalWidth = width * numDigits;

        //Draw digits
        for(int i = 0; i < numDigits; i++){
            int digit = Character.getNumericValue(numberString.charAt(i));

            /*I get a null pointer exception when this method or the dispose() method are called. The _numbers[digit] == null, or even if I switch it for _numbers[0] it is still null. Why?*/
            sb.draw(_numbers[digit], x - totalWidth/2 + i*width, y - height/2, width, height);
        }
    }

    public void dispose(){
        //I get null pointer exception
        for(Texture texture: _numbers){
            texture.dispose();
        }
    }
}

What may be happening here? The constructor of this function has to be called always before any method and this will guarantee that the textures are always loaded right? So why am I getting a null pointer exception?

Thanks!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Daniel Oliveira
  • 1,280
  • 14
  • 36
  • @John3136 I know what a NullPointerException is, I just can´t find the error here. I really think you should read the whole question before you take an action. – Daniel Oliveira Dec 20 '16 at 03:46
  • 2
    Your constructor. Every time over the loop you made a `new Texture[10]`. When the loop exits, only `_numbers[9]` will not be null – OneCricketeer Dec 20 '16 at 03:46
  • 2
    Shouldn't matter that you know what it is - debug, set breakpoints. Print values. Figure out the *why*. – OneCricketeer Dec 20 '16 at 03:46
  • @cricket_007 thanks a lot! It solved by problem. I did not notice that expression what inside the loop. – Daniel Oliveira Dec 20 '16 at 03:48
  • Right. You get a NPE within dispose at `texture.dispose()` so at least one `texture` value is null. So you should look at the only place you initialize that array. – OneCricketeer Dec 20 '16 at 03:50

1 Answers1

1
 _numbers = new Texture[10];
 _numbers[i] = new Texture("font_"+i+".png");

In the loop you create a new array each iteration, this means that when the loop ends you will have a new array with just the last element initialized. Move the creation of the array out of the loop.

Kiskae
  • 24,655
  • 2
  • 77
  • 74