0

I tried to make flappy bird for my assignment, but I got error like this

Exception in thread "Thread-2" java.lang.NullPointerException
at main.Main.update(Main.java:84)
at main.Main.run(Main.java:64)
at java.lang.Thread.run(Unknown Source)

It says that my bird.update() is null or something but I can't resolve it.

I tried to change image to rectangle in bird class and it's working, but I need to use the image for my assignment

And this my code for main class

package main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import infra.ControlSystem;

import javax.imageio.ImageIO;
public class Main extends Canvas implements Runnable,KeyListener{

    /**
     * 
     */
    private static final long serialVersionUID = 3196520274556633778L;
    public static final int WIDTH = 800, HEIGHT = 600;
    private Thread thread;
    private Random r;
    private Tube tube;
    private Bird bird;

    private boolean running = false;
    public Main(){
      new Window(WIDTH,HEIGHT,"Altenative Bird", this);
      r = new Random();
      addKeyListener(this);
      tube = new Tube(80);
      BufferedImage sheets = null;
      try {
          sheets = ImageIO.read(getClass().getResource("/twitter.png"));

      } catch (IOException e) {
           // TODO Auto-generated catch block
            e.printStackTrace();
      }
      if(sheets == null){
           System.out.println("damn it's null");
      }else{
           System.out.println("hi");
      }
      bird = new Bird(100,Main.HEIGHT/2,tube.tubes,sheets);
    }  
    public synchronized void start(){
        thread = new Thread(this);
        thread.start();
        running = true;
    }

    public synchronized void stop(){
        try{
                thread.join();
                running = false;
        }catch(Exception e){
                e.printStackTrace();
        }
    }
    @Override
    public void run(){
        int frames = 0;
        long lastTime = System.nanoTime();
        double amountOFTicks = 60.0;
        double ns = 1000000000 / amountOFTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        while(running){
            long now  =System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >=1 ){
                update();
                render();
                    // TODO Auto-generated catch block

                delta--;
                frames++;

            }

            if(System.currentTimeMillis() - timer>=1000){
                timer+=1000;
                System.out.println("FPS: "+frames);
                frames=0;
            }
        }
    }

    private void update(){
        tube.update();
        System.out.println(bird);
        bird.update();
    }

    private void render(){
        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null){
            this.createBufferStrategy(3);
            return;
        }
        sheets = ImageIO.read(getClass().getResource("/twitter.png"));
        texture[0] = sheets.getSubimage(0, 0, 150, 150);
        Graphics g = bs.getDrawGraphics();
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        //BufferedImage bi = ImageIO.read(new File("Res//forest.png"));
        //g.drawImage(bi, 0, 0, getWidth(), getHeight(), this);

        tube.render(g);
        bird.render(g);
        g.dispose();
        bs.show();


    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub
        if(arg0.getKeyCode()==KeyEvent.VK_SPACE){
            bird.pressed = true;
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub
        if(arg0.getKeyCode()==KeyEvent.VK_SPACE){
            bird.pressed = false;
        }
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Main();
    }

}

and this is the code for my bird class

    package main;

import java.awt.Color;
import java.awt.Graphics;
import java.awt. Rectangle;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;

public class Bird extends Rectangle{
    private int spd=10;
    public boolean pressed=false;
    private BufferedImage sheets;
    private BufferedImage[] texture;
    private ArrayList<Rectangle> tubes;
    public Bird(int x,int y,ArrayList<Rectangle> tubes,BufferedImage sheets){  
        setBounds(x,y,32,23);
        this.tubes = tubes;
        texture = new BufferedImage[4];
            texture[0] = sheets.getSubimage(0, 0, 150, 150);
            texture[1] = sheets.getSubimage(150, 0, 150, 150);
            texture[2] = sheets.getSubimage(300, 0, 150, 150);
            texture[3] = sheets.getSubimage(450, 0, 150, 150);
    }
    public void update(){
        if(pressed){
            y-=spd;
        }else{
            y+=spd; 
        }
            for(int i=0;i<tubes.size();i++){    
                if(this.intersects(tubes.get(i))){  
                    System.exit(0);
                }
            }
            if(y==550){
                System.exit(0);   
            }
    }

    public void render(Graphics g){
        //g.setColor(Color.gray);
        g.drawImage(texture[0], x, y, width, height, null);
        //g.fillRect(x, y, width, height);

    }
}

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Please double check the lines that throws the exceptions and report back. In other words, re-run the application, get the stacktrace, and let us know exactly which lines are involved in throwing the exception. – Hovercraft Full Of Eels Jul 02 '17 at 11:56
  • My bet is that you're using the wrong path to your image resource. One tip -- don't re-read the image resource multiple times as you're doing, but read them in once in the constructor and then save to variables. And after reading them in, do a null check on them within the constructor, at least initially, to be sure that they're not null. – Hovercraft Full Of Eels Jul 02 '17 at 11:59
  • how to get the stacktrace?? sorry i'm new to java – Kevin Nathaniel Jul 02 '17 at 12:04
  • The JVM gives it to you when an exception is thrown, and in fact you've posted part of it at the top of your question, starting with `Exception in thread "Thread-2" java.lang.NullPointerException ....`. The line numbers in it that refer to **your** program are key. Please look at [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) as it will tell you much more about how to debug NPE's. – Hovercraft Full Of Eels Jul 02 '17 at 12:06
  • If you've not changed your program, then you need to let us know which lines are `Main.java:84` and `Main.java:64`. If you have changed your program, then get the new line numbers from the stacktrace and let us know which lines they are. – Hovercraft Full Of Eels Jul 02 '17 at 12:15
  • i already tried what you told me, i didn't find my image is null. – Kevin Nathaniel Jul 02 '17 at 12:17
  • Crap, I think I see your problem. Put this line, `new Window(WIDTH,HEIGHT,"Altenative Bird", this);` at the ***BOTTOM*** of your constructor, **after** you've created your Bird object and assigned it to the bird variable. I'll bet that the Window (JFrame?) is trying to render your bird before it's been initialized. – Hovercraft Full Of Eels Jul 02 '17 at 12:21
  • Your problem is that you've got things within the Main constructor that don't belong there. Rendering code should only be called **after** an object has been fully constructed. If this were my app, I'd get the `new Window(...)` out of the constructor completely and would only call it **after** Main has been fully realized. – Hovercraft Full Of Eels Jul 02 '17 at 12:25
  • it's working thanks dude, so i should get the new window out of constructor then..?? – Kevin Nathaniel Jul 02 '17 at 12:35

0 Answers0