Вызов TargetException и исключение нулевого указателя в Android

У меня есть эта часть кода в проекте, в которой я получаю "исключение нулевого указателя" в этой строке CGRect shipRect = CGRect.make(ship.getPosition().x - (ship.getContentSize().width),, но я объявил значение корабля как protected CCSprite ship; в классе, но все еще получаю ошибку "исключение нулевого указателя".
вот полный код

public void update(float dt)
{


            for (CCSprite target : _targets)
              {
                    CGRect targetRect = CGRect.make(target.getPosition().x - (target.getContentSize().width),
                                                                              target.getPosition().y -
                                                                            (target.getContentSize().height),
                                                            target.getContentSize().width,target.getContentSize().height);

                    System.out.println("shipstodelete : " + ship);

                    CGRect shipRect = CGRect.make(ship.getPosition().x - (ship.getContentSize().width),
                            ship.getPosition().y - (ship.getContentSize().height),
                            ship.getContentSize().width,ship.getContentSize().height);



                 if (CGRect.intersects(targetRect, shipRect))
                    {

                    this.removeChild(ship, true);
                    //removeChild(ship, true);
                    }
              }   

это код для спрайта корабля в конструкторе

CCSprite ship = CCSprite.sprite("ship150.png");
     ship.setPosition(CGPoint.ccp(25,100));
     ship.setAnchorPoint(CGPoint.ccp(0,0));
     ship.setTag(4);
        addChild(ship);

вывод логарифма

 06-10 04:53:13.463: W/System.err(1138): java.lang.reflect.InvocationTargetException
 06-10 04:53:13.473: W/System.err(1138):    at    java.lang.reflect.Method.invokeNative(Native Method)
 06-10 04:53:13.473: W/System.err(1138):    at  java.lang.reflect.Method.invoke(Method.java:511)
 06-10 04:53:13.473: W/System.err(1138):    at org.cocos2d.actions.CCTimer.update(CCTimer.java:82)
  06-10 04:53:13.473: W/System.err(1138):   at org.cocos2d.actions.CCScheduler.tick(CCScheduler.java:253)
 06-10 04:53:13.473: W/System.err(1138):    at org.cocos2d.nodes.CCDirector.drawCCScene(CCDirector.java:679)
 06-10 04:53:13.473: W/System.err(1138):    at org.cocos2d.nodes.CCDirector.onDrawFrame(CCDirector.java:649)
 06-10 04:53:13.483: W/System.err(1138):    at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
 06-10 04:53:13.483: W/System.err(1138):    at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
 06-10 04:53:13.483: W/System.err(1138): Caused by: java.lang.NullPointerException
 06-10 04:53:13.483: W/System.err(1138):    at com.trialcocos.GameL.update(GameL.java:183)
 06-10 04:53:13.483: W/System.err(1138):    ... 8 more

comment
Где вы устанавливаете «защищенный корабль CCSprite»? к значению?   -  person Larry McKenzie    schedule 10.06.2013
comment
да на самом деле не отвечает на мой вопрос... Где вы устанавливаете стоимость корабля? Я опубликую ответ, чтобы объяснить больше того, что я имею в виду...   -  person Larry McKenzie    schedule 10.06.2013


Ответы (1)


Вам нужно установить для защищенного атрибута значение, иначе оно равно нулю.

protected CCSprite ship;

public void update(float dt){
    for (CCSprite target : _targets){
        CGRect targetRect = CGRect.make(target.getPosition().x - (target.getContentSize().width), target.getPosition().y - (target.getContentSize().height), target.getContentSize().width,target.getContentSize().height);
        System.out.println("shipstodelete : " + ship);
        CGRect shipRect = CGRect.make(ship.getPosition().x - (ship.getContentSize().width), ship.getPosition().y - (ship.getContentSize().height), ship.getContentSize().width,ship.getContentSize().height);
        if (CGRect.intersects(targetRect, shipRect)){
            this.removeChild(ship, true);
            //removeChild(ship, true);
        }
    }
}
...

public void someOtherMethodYouDontMention(){
    //Notice I set the previously declared ship value not a new ship value
    ship = CCSprite.sprite("ship150.png");
    ship.setPosition(CGPoint.ccp(25,100));
    ship.setAnchorPoint(CGPoint.ccp(0,0));
    ship.setTag(4);
    addChild(ship);
}
person Larry McKenzie    schedule 10.06.2013
comment
я не помещал код для спрайта (корабль) в addTarget(), только объявил значение для корабля в конструкторе, это ошибка, которую я сделал, а также добавил _ships.remove (спрайт); этот фрагмент кода в public void spriteMoveFinished(Object sender), так что все заработало, в любом случае спасибо :) @Larry McKenzie - person DD.; 14.06.2013