gpt4 book ai didi

java - Android - 构造函数变量中的空指针异常

转载 作者:行者123 更新时间:2023-12-01 18:43:18 24 4
gpt4 key购买 nike

我正在为 Android 应用程序中的 GridView 开发自定义适配器。其定义如下:

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;
}

}

我在 Activity 的 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 构造函数。我不知道为什么在对象创建时引用该数组的元素时会抛出空指针异常...

最佳答案

由于您编写了一个初始化程序 block 并使用了空的board。

public int[] pieces = new int [64];

//您在这里启动了一个 block 。请注意board尚未初始化。

{
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;
}
}
};

您要做的就是创建一个名为 intializer 的方法并在那里执行

public int[] pieces = new int [64];
private void intialize(){

{
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;
intialize();
}

关于java - Android - 构造函数变量中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19007490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com