Null pointer exception when attaching custom appstate

Hi all, its my first of week of learning Jmonkey Engine 3 and 2nd week of learning java. I was previously developing in c#. The prroblem is, I am following Appstates tuttorial . here is my main simple application code
/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package mygame;

import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AppState;

/**
*

  • @author Hassan Sohail
    */
    public class MainCallingClass extends SimpleApplication{

    public static void main(String[] args)
    {
    MainCallingClass app;
    app=new MainCallingClass();
    app.start();
    }

    @Override
    public void simpleInitApp() {

    stateManager.attach(new MainMenuAppState());
    

    }

    @Override
    public void simpleUpdate(float tpf)
    {

    }
    }
    Here is my custom appstate code
    /*

  • To change this template, choose Tools | Templates

  • and open the template in the editor.
    */
    package mygame;

import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.input.ChaseCamera;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.LightScatteringFilter;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.shadow.PssmShadowRenderer;
import com.jme3.util.SkyFactory;

/**
*

  • @author Hassan Sohail
    */
    public class MainMenuAppState extends AbstractAppState {
    private MainCallingClass app;
    private Node rootNode;

      private Spatial sceneModel;  ///// for loading our scene
    

private BulletAppState bulletAppState;// for physics
private RigidBodyControl landscape; // for collision of terrein
private Controls myplayercontrols=new Controls();

//Temporary vectors used on each frame.
//They here to avoid instanciating new vectors on each frame
private Vector3f camDir = new Vector3f();
private Vector3f camLeft = new Vector3f();

public Spatial geom;
@Override

public void initialize(AppStateManager stateManager,Application App)
{
    //intitailizing appstate
   // super.initialize(stateManager, app);
    System.out.println("before before"); 
    App=(MainCallingClass)app;
    System.out.println("before"); 
    
    this.rootNode=app.getRootNode();
    System.out.println("after"); 
    ////////////////
      sceneModel = app.getAssetManager().loadModel("Scenes/newScene.j3o");
    bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
 setUpKeys();

// setUpLight();

CollisionShape sceneShape =
        CollisionShapeFactory.createMeshShape((Node) sceneModel);
landscape = new RigidBodyControl(sceneShape, 0);
sceneModel.addControl(landscape);

 CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1);
myplayercontrols.player = new CharacterControl(capsuleShape, 1.15f);
myplayercontrols.player.setJumpSpeed(20);
myplayercontrols.player.setFallSpeed(30);
myplayercontrols.player.setGravity(30);
myplayercontrols.player.setPhysicsLocation(new Vector3f(32f, 20f, -8f));

// cam.setLocation(player.getPhysicsLocation());

    /////////////// Setting up Sun
    //cam.setLocation(new Vector3f(200, 0, 0));
  //  cam.setRotation(new Quaternion(0.010414706f, 0.9874893f, 0.13880467f, -0.07409228f));

// flyCam.setEnabled(false);
this.app.getFlyByCamera().setMoveSpeed(50);

    //Spatial car = assetManager.loadModel("Models/car/car.j3o");
   
   sceneModel.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
//  

    rootNode.attachChild(sceneModel);
    //rootNode.addControl(player);
    //cam.
    //rootNode.removeControl(player);

    // load sky
    rootNode.attachChild(SkyFactory.createSky(this.app.getAssetManager(), "Scenes/FullskiesBlueClear03.dds", false));

    DirectionalLight sun = new DirectionalLight();
    Vector3f lightDir = new Vector3f(-0.12f, -0.3729129f, 0.74847335f);
    sun.setDirection(lightDir);
    sun.setColor(ColorRGBA.White.clone().multLocal(2));
    sceneModel.addLight(sun);

    PssmShadowRenderer pssmRenderer = new PssmShadowRenderer(this.app.getAssetManager(),1024,4);
    pssmRenderer.setDirection(lightDir);
    pssmRenderer.setShadowIntensity(0.55f);


    FilterPostProcessor fpp = new FilterPostProcessor(this.app.getAssetManager());

    Vector3f lightPos = lightDir.multLocal(-3000);    

    LightScatteringFilter filter = new LightScatteringFilter(lightPos);
 
    fpp.addFilter(filter);


    this.app.getViewPort().addProcessor(fpp);
    
    
    ///////////////  Sun done ;)
    
    ///////////////  adding cube
   
  geom = this.app.getAssetManager().loadModel("Models/cube/cube.j3o");
  Material mat=new Material(this.app.getAssetManager(), 
    "Common/MatDefs/Misc/Unshaded.j3md");
  mat.setColor("Color",ColorRGBA.Blue);
  geom.setMaterial(mat);
    //geom.addControl(player);
    
    rootNode.attachChild(geom);
    
    //rootNode.attachChild(car);
/////////////////////// Cube added
bulletAppState.getPhysicsSpace().add(landscape);
bulletAppState.getPhysicsSpace().add(myplayercontrols.player);

/////////////////Now adding chaseCamera
this.app.getFlyByCamera().setEnabled(false);
ChaseCamera chasecam=new ChaseCamera(this.app.getCamera(),geom,this.app.getInputManager());
chasecam.setSmoothMotion(true);
    
}
private void setUpKeys() {
this.app.getInputManager().addMapping("Left", new KeyTrigger(KeyInput.KEY_A));
this.app.getInputManager().addMapping("Right", new KeyTrigger(KeyInput.KEY_D));
this.app.getInputManager().addMapping("Up", new KeyTrigger(KeyInput.KEY_W));
this.app.getInputManager().addMapping("Down", new KeyTrigger(KeyInput.KEY_S));
this.app.getInputManager().addMapping("Jump", new KeyTrigger(KeyInput.KEY_SPACE));
this.app.getInputManager().addMapping("Menu", new KeyTrigger(KeyInput.KEY_RSHIFT));

this.app.getInputManager().addListener(myplayercontrols, "Left");

this.app.getInputManager().addListener(myplayercontrols, "Right");

this.app.getInputManager().addListener(myplayercontrols, "Up");

this.app.getInputManager().addListener(myplayercontrols, "Down")

this.app.getInputManager().addListener(myplayercontrols, "Jump");

this.app.getInputManager().addListener(myplayercontrols, "Menu");

}

@Override

public void update(float tpf)

{

    super.update(tpf);
    
    camDir.set(this.app.getCamera().getDirection()).multLocal(0.6f);
    camLeft.set(this.app.getCamera().getLeft()).multLocal(0.4f);
    myplayercontrols.walkDirection.set(0, 0, 0);
    if (myplayercontrols.left) {
        myplayercontrols.walkDirection.addLocal(camLeft);
        System.out.print("left");
    }
    if (myplayercontrols.right) {
        myplayercontrols.walkDirection.addLocal(camLeft.negate());
    }
    if (myplayercontrols.up) {
        myplayercontrols.walkDirection.addLocal(camDir);
    }
    if (myplayercontrols.down) {
        myplayercontrols.walkDirection.addLocal(camDir.negate());
    }
    if(myplayercontrols.menu)
    {
     //   stateManager.detach(get);
    }
    myplayercontrols.player.setWalkDirection(myplayercontrols.walkDirection);
    geom.setLocalTranslation(myplayercontrols.player.getPhysicsLocation());
}

}
I know its kind of messy but not my final version.
I get null pointer exception and the error points to

    this.rootNode=app.getRootNode();

if i comment or remove this line error moves to next line.

      sceneModel = app.getAssetManager().loadModel("Scenes/newScene.j3o");

I tried everything i could. Please help me if i dont understand somehing .
Thanks in Advance

This is not correct!
app is null, because of this you get a null pointer, when you call app.someMethod();

1 Like

Please write some example as of what should i do . this appstate thing is getting the best of me :confused: .

should i do

app=new MainCallingClass();

it isnt helping

Thanks Domenic bro. hats off to you for pointing me right direction :smile:

The actual solution was

app=(MainCallingClass) App;

Word of advice…

Don’t ever set yourself up for subtle problems like that. Use the same case if you want to use the same name… then if you want to refer to the local instance variable over the parameter:
this.app = (MainCallingClass)app;

You’ve bit off a big chunk while trying to learn Java and 3D and JME all at once. Like learning to ride a bike and shave at the same time.

Some more words of advice for asking for help:

  1. don’t mention an exception unless you provide the stack trace. The name of the exception is the least important information and is only one step above saying “there is a problem”.
  2. https://hub.jmonkeyengine.org/t/how-to-type-code-blocks

Thanks for the advice. It was my first post here. Will keep that in mind :slight_smile:.

1 Like

Also another worde of advice here: AppStates can be coded game-independent so you can re-use them.
Here you destroy that independency by binding it to that MainClassThing.

If you had a class you re-use for other games then this is fine but by simply looking at your code, it should be enough to cast to SimpleApplication or LegacyApplication (First 3.0, second v3.1) so it works for everything.

That’s the idea of appstates essentially

2 Likes