我正在为 android 应用程序中的网格视图开发自定义适配器。定义如下:
public class BoardAdapter extends BaseAdapter {
public static final int EMPTY = 0;
public static final int RED = 1;
public static final int BLACK = 2;
public static final int RED_PROMOTED = 3;
public static final int BLACK_PROMOTED = 4;
Context context;
int[][] board = null;
public int[] pieces = new int [64];
{
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
//null pointer exception here
if(board[i][j] == RED)
{
pieces[8*i+j] = R.drawable.red_piece;
}
else if(board[i][j] == BLACK)
{
pieces[8*i+j] = R.drawable.black_piece;
}
else pieces[8*i+j] = 0;
}
}
};
public BoardAdapter (Context ctx, int[][] board)
{
this.context = ctx;
this.board = board;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return pieces.length;
}
@Override
public Object getItem(int pos) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
return pieces[pos];
}
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(context);
imageView.setImageResource(pieces[pos]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
return imageView;
}
}
我在活动的 onCreate 方法中创建对象:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
board = (GridView) findViewById (R.id.board);
game.printBoard();
//null pointer exception here
board.setAdapter(new BoardAdapter(this, game.getBoard()));
}
当我打印板时,日志显示正确的值。所以我确信,我将一个初始化的板传递给 BoardAdapter 构造函数。我不知道,为什么在创建对象时引用该数组的元素时会引发空指针异常...