我正在努力将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方法中,我发现'迷宫'为空且参数有效。我还发现迷宫在Mazebuilder的构建方法中设置为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与迷宫迷宫的类型不同......很明显我无法创建一个设置GA =迷宫的构造函数......我很困惑。
同样,我非常感谢任何帮助和耐心。这对新手来说是一场噩梦。
答案 0 :(得分:3)
您需要为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);