Matt
Matt

Reputation: 1704

Null pointer dereference exception on non-null object

I'm using libGDX 1.5.6 and Android Studio 1.1.0. I want to have an activity that displays an ApplicationListener to the user (ultimately rendering models in a 3d space and viewing them with a camera).

I had a Android app that successfully switched between activities (super simple). Then I swapped out the logic in the onCreate method (of the activity being switched to) with libGDX launching logic from this tutorial: http://steigert.blogspot.com/2012/02/1-libgdx-tutorial-introduction.html

I've worked through many many build errors on my own and have run into one that stumps me: Attempt to invoke virtual method 'void com.badlogic.gdx.graphics.g3d.ModelBatch.begin(com.badlogic.gdx.graphics.Camera) ' on a null object reference (at com.example.matthew.constellate.Stargazer.render(Stargazer.java:53))

Obviously something thinks my camera is null, but based on this source, I don't see how that is possible:

public class Stargazer implements ApplicationListener
{
public Model model;
public PerspectiveCamera cam;
public ModelInstance instance;
public ModelBatch modelBatch;

@Override
public void create()
{
    // Need a camera
    cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.position.set(0f, 0f, 0f);
    cam.near = 1f;
    cam.far = 300f;
    cam.update();

    // Create obj to test rendering
    ModelBuilder modelBuilder = new ModelBuilder();

    model = modelBuilder.createBox(5f, 5f, 5f,
            new Material(ColorAttribute.createDiffuse(Color.RED)),
            VertexAttributes.Usage.Position |     VertexAttributes.Usage.Normal);

    instance = new ModelInstance(model);
}

@Override
public void render()
{
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(),     Gdx.graphics.getHeight());
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    modelBatch.begin(cam); // LINE 53
    modelBatch.render(instance);
    modelBatch.end();
}

...

which is being triggered with this launcher:

protected void onCreate(Bundle savedInstanceState)
{
    boolean useOpenGLES2 = false;

    super.onCreate(savedInstanceState);
    initialize(new Stargazer());
}

Does anyone see something obvious I'm missing?

Upvotes: 0

Views: 836

Answers (2)

inmyth
inmyth

Reputation: 9050

modelBatch has not been instantiated.

Upvotes: 4

Sumit Surana
Sumit Surana

Reputation: 1584

I would suggest to add cam object inside the render method.

Upvotes: 0

Related Questions