代码之家  ›  专栏  ›  技术社区  ›  Pawan Chaurasiya

在Vector中插入元素时,我收到错误java.lang.NullPointerException

  •  0
  • Pawan Chaurasiya  · 技术社区  · 11 年前

    当我尝试运行以下程序时,它会抛出 java.lang.NullPointerException 。我不明白,为什么在将元素插入向量时会出现此错误。请帮助我解决以下问题。提前感谢。

        public class GameMidlet extends MIDlet implements CommandListener {
    
        GameCanvas game;
        Display display;
        Command exitCommand;
        Command restartCommand;
        Vector mGameCanvasList;
    
        public void startApp() {
    
            display  = Display.getDisplay(this);
            game = new GameCanvas();
    
            //i am getting error at here when game object inset in vector
            mGameCanvasList.addElement(game);
    
            GameCanvas fistList = (GameCanvas) mGameCanvasList.elementAt(0);
            display.setCurrent(fistList);
    
            exitCommand     = new Command("Exit", Command.EXIT, 0);
            restartCommand  = new Command("Restart", Command.OK, 0);
    
            fistList.addCommand(exitCommand);
            fistList.addCommand(restartCommand);
    
            fistList.setCommandListener(this);
            fistList.setCommandListener(this);
            fistList.startThread();
    
        }
    
        public void pauseApp() {
        }
    
        public void destroyApp(boolean unconditional) {
        }
    
        public void commandAction(Command c, Displayable d) {
    
            if(c == exitCommand){
    //            System.out.println("Exit");
    
                destroyApp(true);
                notifyDestroyed();
            }
    
            if(c == restartCommand){
    //            game
            }
    
        }
    }
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   Ray    11 年前

    您从未实例化 Vector 。在错误行之前的某个位置,必须执行以下操作:

    mGameCanvasList = new Vector();