尝试启动活动时出现NullException

时间:2015-12-03 18:36:01

标签: java android

我希望我的物体撞墙。当我的精灵碰撞时,我想发布一个新的屏幕,上面写着“你崩溃了”。

我不断收到同样的错误!

    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);

}

}

这是我创建意图的地方:

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

这是错误:

 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是Activity,它顶部有一个“gameView”

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;
       }

当精灵碰撞时,我希望它打开一个新的活动,主精灵位于屏幕的底部,并有自己的类Sprite.java,其他每个精灵都由TrafficSprite.java控制

3 个答案:

答案 0 :(得分:0)

试试这段代码:

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

}

并在新的Activity中设置一个带有要显示的文本的TextView。

答案 1 :(得分:0)

也许您需要当前活动的conext,通常是MainActivity:

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

}

考虑到您使用的是明确的意图,因此您需要运行确切的类,并使用上下文作为documentation says

进行解析

答案 2 :(得分:0)

根据堆栈跟踪,您的错误发生here。问题是mBasenull,这意味着您的上下文未初始化。这可能由于各种原因而发生 请检查以下内容:

是清单中列出的这种活动吗? Activty的onCreate方法是否正确完成? 这个方法是在onCreate之后调用的吗?

我确信上述问题之一就是问题。

修改
要解决您的问题:

<{1>}活动中的

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

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); } 的类TrafficSprite,但它的上下文创建方法根本没有被调用(例如Activity没有叫)。

<强> EDIT2:

SurfaceView类中已有一个getContext()方法,因此可以使用。

onCreate

由于您的SurfaceView具有activty的上下文,因此这也应该很好。