0

I want my object to hit a wall. When my sprites collide I want to launch a new screen saying "You crashed".

I keep getting the same error though!

    package com.example.rushhour;

    import java.util.Random;

    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Rect;
    import android.media.MediaPlayer;


public class TrafficSprite extends PlayScreen {
       Random rand = new Random();
       private int x = 5;
       private int y = 30;
       private int xSpeed = 0;
       private int ySpeed = 0;
       private GameView gameView;
       private PlayScreen playScreen;
       private Sprite sprite;
       private Bitmap bmp;
       private int width;
       private int height;
       private MediaPlayer crashsound;



       public TrafficSprite(GameView gameView, Bitmap bmp) {
             this.gameView = gameView;
             this.playScreen = playScreen;
             this.sprite = sprite;
             this.bmp = bmp;
             this.width = bmp.getWidth();
             this.height = bmp.getHeight();
             System.out.println(gameView.getWidth());
             int randomwidth = gameView.getWidth();
             Math.abs(randomwidth);
             x=rand.nextInt(760);
       }



       private void update(){
        collision();   
        ySpeed = 10;
        y+=ySpeed;



       }

       **private void collision(){
           Rect policerect = new Rect(Sprite.getPolicex(),Sprite.getPolicey(),Sprite.getPolicex()+Sprite.getPoliceWidth(),Sprite.getPolicey()+Sprite.getPoliceHeight());
           Rect trafficsprite = new Rect(x,y,x+bmp.getWidth(),y+bmp.getHeight());
           if (Rect.intersects(policerect, trafficsprite)){
               GameView.getCrashSound().start();
               CrashScreen();

           }

       }

       public void CrashScreen(){
        System.out.println("hi");
          Intent intent = new Intent(this, Crash.class);
          startActivity(intent);

    }**



       public void drawTraffic(Canvas canvas) {

                 update();
                 Rect src = new Rect (0,0,width,height);
                 Rect dst = new Rect (x,y,x+width,y+height);
                 canvas.drawBitmap(bmp, src, dst, null);

}

}

This is where I create the intent:

public void CrashScreen(){
            System.out.println("hi");
              Intent intent = new Intent(this, Crash.class);
              startActivity(intent);

This is the error:

 FATAL EXCEPTION: Thread-6714
12-03 17:57:46.497: E/AndroidRuntime(6013): Process: com.example.rushhour, PID: 6013
12-03 17:57:46.497: E/AndroidRuntime(6013): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
12-03 17:57:46.497: E/AndroidRuntime(6013):     at android.content.ContextWrapper.getPackageName(ContextWrapper.java:131)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at android.content.ComponentName.<init>(ComponentName.java:77)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at android.content.Intent.<init>(Intent.java:3996)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at com.example.rushhour.TrafficSprite.CrashScreen(TrafficSprite.java:65)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at com.example.rushhour.TrafficSprite.collision(TrafficSprite.java:58)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at com.example.rushhour.TrafficSprite.update(TrafficSprite.java:45)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at com.example.rushhour.TrafficSprite.drawTraffic(TrafficSprite.java:82)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at com.example.rushhour.GameView.createTraffic(GameView.java:218)
12-03 17:57:46.497: E/AndroidRuntime(6013):     at com.example.rushhour.GameLoopThread.run(GameLoopThread.java:25)

Play Screen is the Activity, it has a "gameView"on top

setContentView(new GameView(this));

Gameview:

package com.example.rushhour;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;



public class GameView extends SurfaceView {
       private Bitmap background,police,audi;
       private Sprite policesprite;
       private TrafficSprite audisprite;

       private List<TrafficSprite> trafficsprites = new ArrayList<TrafficSprite>();
       private SurfaceHolder holder;
       private GameLoopThread gameLoopThread;
       private int x = 0;
       final Handler handler = new Handler();
       private int i =-1;
       public static MediaPlayer crashsound;


       public GameView(Context context) {
             super(context);
             gameLoopThread = new GameLoopThread(this);
             holder = getHolder();
             crashsound = MediaPlayer.create(context, R.raw.crash);
             holder.addCallback(new SurfaceHolder.Callback() {

                    @Override
                    public void surfaceDestroyed(SurfaceHolder holder) {
                        boolean retry = true;
                        gameLoopThread.setRunning(false);
                        while (retry){
                               try {
                                     gameLoopThread.join();
                                     retry = false;
                               } catch (InterruptedException e) {
                               }
                        }

                    }

                    @Override
                    public void surfaceCreated(SurfaceHolder holder) {
                        createSprites();
                        gameLoopThread.setRunning(true);
                        gameLoopThread.start();

                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder holder, int format,
                                  int width, int height) {
                    }
             });

             background = BitmapFactory.decodeResource(getResources(), R.drawable.playbackground);
             police = BitmapFactory.decodeResource(getResources(), R.drawable.policered);
             audi = BitmapFactory.decodeResource(getResources(), R.drawable.audi);
             policesprite = new Sprite(this,police);
             audisprite = new TrafficSprite(this,audi);




       }

       private void createSprites() {
           final int[] spriteID = { 
                   R.drawable.amb,
                   R.drawable.audi,
                   R.drawable.car,
                   R.drawable.mini,
                   R.drawable.truck,
                   R.drawable.taxi,
                   R.drawable.van
                   // etc for as many images you have
           };
           new Thread(new Runnable() {
                public void run() {
                    Looper.prepare();
                    for(int i = 0; i < 6; i++) {
                        if (i == 5){
                            mediumspeed();
                        }
                        Random generator = new Random();
                        int randomImageId = spriteID[generator.nextInt(spriteID.length)];
                        trafficsprites.add(createSprite(randomImageId));
                        try
                        {
                            Thread.sleep(3000); //Waits for 1 second
                        }
                        catch(InterruptedException e)
                        {
                            e.printStackTrace();
                        }


                    }
                }
            }).start();

       }

       public void mediumspeed(){

           final int[] spriteID = { 
                   R.drawable.amb,
                   R.drawable.audi,
                   R.drawable.car,
                   R.drawable.mini,
                   R.drawable.truck,
                   R.drawable.taxi,
                   R.drawable.van
                   // etc for as many images you have
           };
           new Thread(new Runnable() {
                public void run() {
                    Looper.prepare();
                    for(int i = 0; i < 6; i++) {
                        if (i==5){
                            fastspeed();
                        }
                    Random generator = new Random();
                    int randomImageId = spriteID[generator.nextInt(spriteID.length)];
                    trafficsprites.add(createSprite(randomImageId));
                    try
                        {
                        Thread.sleep(1850); //Waits for 1 second
                        }
                    catch(InterruptedException e)
                        {
                        e.printStackTrace();
                        }


                    }
                }
            }).start();


       }



      public void fastspeed(){

           final int[] spriteID = { 
                   R.drawable.amb,
                   R.drawable.audi,
                   R.drawable.car,
                   R.drawable.mini,
                   R.drawable.truck,
                   R.drawable.taxi,
                   R.drawable.van
                   // etc for as many images you have
           };
           new Thread(new Runnable() {
                public void run() {
                    Looper.prepare();
                    for(int i = 0; i < 6; i++) {
                    Random generator = new Random();
                    int randomImageId = spriteID[generator.nextInt(spriteID.length)];
                    trafficsprites.add(createSprite(randomImageId));
                    try
                        {
                        Thread.sleep(1200); //Waits for 1 second
                        }
                    catch(InterruptedException e)
                        {
                        e.printStackTrace();
                        }


                    }
                }
            }).start();


       }




       private TrafficSprite createSprite(int resouce) {
           Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
           return new TrafficSprite(this,bmp);
     }





        @Override
       protected void onDraw(Canvas canvas){
                 canvas.drawBitmap(background, 0, 0, null);
                 policesprite.onDraw(canvas);
    }

       protected void createTraffic(Canvas canvas){
           for (TrafficSprite trafficsprite : trafficsprites) {
               trafficsprite.drawTraffic(canvas);
        }

       }
       protected void createTraffic1(Canvas canvas){
           trafficsprites.get(1).drawTraffic(canvas);

       }

       public static MediaPlayer getCrashSound(){
           return crashsound;
       }

When sprites collide i want it to open a new activity, the master sprite is at the bottom of the screen and has its own class Sprite.java, every other sprite is controlled by TrafficSprite.java

3 Answers3

0

Try this code:

public void CrashScreen(){
      Intent intent = new Intent(this, Crash.class);
      startActivity(intent);

}

and in the new Activity set a TextView with the text to show.

Raza Ali Poonja
  • 1,086
  • 8
  • 16
0

Maybe you need the conext from your current activity, usually the MainActivity:

public void CrashScreen(){
      Intent intent = new Intent(getActivity().getApplicationContext(), Crash.class);
      startActivity(intent);

}

Take into account you are using an explicit intent, therefore you need the exact class to be run, and it is resolved using a context as the documentation says

lgallard
  • 462
  • 3
  • 10
0

According to the stack trace, your error happens here. The problem is mBase is null, this means your context is not initialized. This can happen due to various reasons.
Please check the followings:

is this activty listed in the manifest?
is the activty's onCreate method finished properly?
is this method called after onCreate?

I am sure one of the above is the problem.

EDIT
To solve your problem:

in the PlayScreen Activity:

new TrafficSprite(this,.....) //refers to the activty

in TrafficSprite:

 private Context cntx;
 public TrafficSprite(Context context,GameView gameView, Bitmap bmp) 
{
    cntx=context;
    ....

 public void CrashScreen(){
        System.out.println("hi");
          Intent intent = new Intent(cntx, Crash.class);
          startActivity(intent);

    }

By doing this, you will have a valid context.

The problem with your solution was, although you created a class(TrafficSprite) which is an Activity, but it's context creating methods does not called at all(e.g. onCreate does not called).

Edit2:

There is a already getContext() method in SurfaceView class, so that can be used.

  public void CrashScreen(){
        System.out.println("hi");
          Intent intent = new Intent(gameView.getContext(), Crash.class);
          startActivity(intent);

    }

As your SurfaceView has the activty's context, thats should be good here too.

csenga
  • 3,819
  • 1
  • 21
  • 31
  • thanks! if i set the activity Crash to run from the main menu, it works fine. – Jason Broomfield Dec 03 '15 at 20:05
  • I am trying to launch it from PlayScreen, this activity has already been launched from the main menu via a button – Jason Broomfield Dec 03 '15 at 20:05
  • public void startPlay(View view) { Intent intent = new Intent(this, PlayScreen.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); backgroundmusic.stop(); startActivity(intent); finish(); } – Jason Broomfield Dec 03 '15 at 20:24
  • TrafficSprite is a gameloop for the cars that i have coming down from the top, it updates their cordinates with the update() method. protected void createTraffic(Canvas canvas){ for (TrafficSprite trafficsprite : trafficsprites) { trafficsprite.drawTraffic(canvas); } – Jason Broomfield Dec 03 '15 at 20:37
  • the onDraw runs that class – Jason Broomfield Dec 03 '15 at 20:37
  • This can be done this way, the trafficsprite objects do not have context. – csenga Dec 03 '15 at 20:40
  • what is the problem ? – csenga Dec 03 '15 at 21:32
  • i have clearly designed this i a bad way. PlayScreen has a view on top of it called "GameView" this is where th sprites are created, so still no context by doing that, ill add the gameview to my question.. – Jason Broomfield Dec 03 '15 at 21:37