我正在将Java Maze应用程序移植到Android。这意味着我要使用给我的Java代码(我没有写这部分),重写一些类(即,将Java图形更改为Android图形,使其可以在Android上运行,并创建Android UI活动) (我已完成)。
当我运行程序时,我收到一个NullPointerException,它抱怨以下行是导致异常的原因:
maze.newMaze(root, cells, dists, startx, starty);
这是错误:
01-19 19:22:53.157: E/AndroidRuntime(638): FATAL EXCEPTION: Thread-79
01-19 19:22:53.157: E/AndroidRuntime(638): java.lang.NullPointerException
01-19 19:22:53.157: E/AndroidRuntime(638): at falstad.MazeBuilder.run(MazeBuilder.java:729)
01-19 19:22:53.157: E/AndroidRuntime(638): at java.lang.Thread.run(Thread.java:856)
错误行显然在MazeBuilder的run方法中,我发现'maze'为null并且参数有效。我还发现在Mazebuilder的build方法中将迷宫设置为null……它通过一个Maze对象并设置maze = mz(迷宫)。
因此,我在Maze.java中找到了调用mazebuilder.build(...)的地方,它位于底部的maze.build()方法中,并以'this'作为参数:
/**
* Method obtains a new Mazebuilder and has it compute new maze,
* it is only used in keyDown()
* @param skill level determines the width, height and number of rooms for the new maze
*/
private void build(int skill) {
// switch screen
state = STATE_GENERATING;
redraw();
// select generation method
switch(method){
case 1 : mazebuilder = new MazeBuilderPrim(); // generate with Prim's algorithm
break ;
case 0: // generate with Falstad's original algorithm (0 and default), note the missing break statement
default : mazebuilder = new MazeBuilder();
break ;
}
// adjust settings and launch generation in a separate thread
mazew = skill_x[skill];
mazeh = skill_y[skill];
int roomcount = skill_rooms[skill];
mazebuilder.build(this, mazew, mazeh, roomcount, skill_partct[skill]);
// mazebuilder calls back by calling newMaze() to return newly generated maze
}
读到这个告诉我参数'this'为空。我已经阅读了Java中的“ this”函数,但仍然不理解,所以我不确定为什么它为null。我也在猜测部分问题是因为我有
mazebuilder = new MazeBuilder()
并不是
mazebuilder = new MazeBuilder(this)
当我尝试添加“ this”参数(如上面的代码行)时,它对我困惑,因为未定义构造函数MazeBuilder(Maze)。但是我的GeneratingActivity GA与Maze迷宫是不同的类型...所以很明显,我无法创建一个设置GA = maze的构造函数...我很困惑。
再次,我非常感谢您的帮助和耐心。对于新手来说,这是一场噩梦。
最佳答案
您将需要为newMazeBuilder
类创建一个参数化的构造函数,以将当前的Activity Context传递为:
public class newMazeBuilder{
public Context context;
public newMazeBuilder(Context context){
this.context=context;
}
///now we context instead of this for passing Context to other components
private void build(int skill) {
// your code here....
mazebuilder.build(context, mazew, mazeh, roomcount, skill_partct[skill]);
}
}
在Activity中创建
newMazeBuilder
类对象为:newMazeBuilder mazebuilder = new newMazeBuilder(Your_Current_Activity.this);