Java:需要帮助指出NullPointerException

时间:2011-12-14 08:29:07

标签: java nullpointerexception

需要帮助指出哪一个导致NullPointerException。我从我的理解中尝试了一切,但仍然没有运气。

import com.threed.jpct.Object3D;

public class HelloShader extends Activity implements OnScaleGestureListener {

    private float ind = 0;
    private boolean doLoop = true;
    private Ticker ticker = new Ticker(15);
    private Object3D snork = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startLoop();    //NullPointerException according to LogCat
    }

    public void initialize(){
        snork = Loader.loadMD2(res.openRawResource(R.raw.image), 0.5f);
        snork.translate(0, 50, 0);
        Texture snorkTexture = new Texture(res.openRawResource(R.raw.imagetexture));
        tm.addTexture("snorkText", snorkTexture);
        snork.setTexture("snorkText");
    }

    public void startLoop(){

        long ticks = 0;

        while (doLoop) {

            ticks = ticker.getTicks();
            if (ticks > 0) {

                animate(ticks); //NullPointerException according to LogCat
            }
        }
    }

    private void animate(long ticks) {
        if (ticks > 0) {
            float ft = (float) ticks;
            ind += 0.02f * ft;
            if (ind > 1) {
                ind -= 1;
            }
            snork.animate(ind, 2);  //NullPointerException according to LogCat

        }
    }

    private static class Ticker {

        private int rate;
        private long s2;

        public static long getTime() {
            return System.currentTimeMillis();
        }

        public Ticker(int tickrateMS) {
            rate = tickrateMS;
            s2 = Ticker.getTime();
        }

        public int getTicks() {
            long i = Ticker.getTime();
            if (i - s2 > rate) {
                int ticks = (int) ((i - s2) / (long) rate);
                s2 += (long) rate * ticks;
                return ticks;
            }
            return 0;
        }
    }

这只是返回错误的代码的一部分,整个代码很长,所以我没有将它们全部发布,因为其他部分与错误无关。我已经为返回NullPointerException的行添加了注释。提前谢谢=)如果您需要其他信息,请告诉我。

3 个答案:

答案 0 :(得分:5)

在调用initialize之前调用的animate之前,您尚未调用onCreate。所以snork为空。

将您的onCreate更改为:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initialize();
    startLoop();
}

答案 1 :(得分:3)

显然,snork为空,这意味着initialize()之前的onCreate()未运行,或Loader.loadMD2()的调用返回null

答案 2 :(得分:0)

当您检查条件s2值仍未分配时,您没有初始化s2。

if (i - s2 > rate) {