开发者

Android Dev - How do you pass Drawables and Buttons through classes?

Im making a chess app and I have a class for each square of the board, for example:

public class square {

public String squarecolor; // white or red
public int row, col;
public chesspiece myPiece = null; // null if empty
public ImageButton myButton;

public Drawable myDrawables[26];

}

in my activity class, each square on the board is an imagebutton. Everytime i try and reference either the drawable or the imagebutton in the square class my program crashes. for example

public class NewGameActivity extends Activity {
        square [][] chessboard = new square[8][8];
        chessboard[0][0].myButton = (ImageButton) findViewById(R.id.aone);
        }

Is there anyway to allow s开发者_运维技巧omething like this to work?


I think this is nothing android specific, but rather a general Java issue.

With

square [][] chessboard = new square[8][8];

you only reserve space for a chess board. You don not allocate any objects.

Then with

 chessboard[0][0].myButton = ...

You try to access the object at (0,0) which has not been allocated itself, so .myButton makes it dereference NULL -> NPE -> crash.

You need to allocate the field first via

chessboard[0][0] = new Square()

And btw: You should start class names with a capital letter like Square

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜