为什么在方法调用中出现此null错误?

时间:2019-09-10 21:51:52

标签: java android object

我收到此错误,原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void com.example.cave.Area.setTiles(android.widget.ImageView)'

我试图让我知道的一切...

//this the main
Area[] area = new Area[9];
    ImageView[] tiles = new ImageView[9];
    for(int i=1; i<=9; i++)
    {
        area[i].setTiles(tiles[i]);
    }
//this is the second class
public class Area  {

ImageView tiles ;

public ImageView getTiles() {
    return tiles;
}

public void setTiles(ImageView tiles) {
    this.tiles = tiles;
}



//
  i want to create tiles, 9 x 9, this is for area 1, than i want another area, 
  area 2, area 3 ... area 9... i want to create imageview array to call it in a 
  class of areas array...
//

1 个答案:

答案 0 :(得分:0)

您已经创建了Area个对象的数组,但是还没有创建对象本身。

//this the main
Area[] area = new Area[9];
ImageView[] tiles = new ImageView[9];

// iterator from 0 to 8, not from 1 to 9
for(int i=0; i<9; i++)
{
    // create array elements, perhaps with constructors, perhaps in some other way
    area[i] = new Area();
    tiles[i] = new Tile();

    area[i].setTiles(tiles[i]);
}