0

I have a simple android app that i am working on, and it animates some squares on the screen when the user taps it, i have a square class, and an array of square objects, however when i try to define the objects in the array then it tells me it cant write to a null array. Here is the code:

Square Class:

public class Square {
int x = 0;
int y = 0;
int width = 0;
int height = 0;
boolean isAvailable = true;
Rect zShape = new Rect();
long xInterval = 0;
long yInterval = 0;

public Square (){

}
}

Canvas Class:

public class MyCanvasView extends View {

Square[] squares;

public MyCanvasView(Context context){
    super(context);
    for(int i = 0; i < 100; i++){
        squares[i] = new Square();
        squares[i].setIntervals();
    }
}
}

the canvas is created in the main Activity and i intended for the squares to be created when the canvas was created. Im not sure what the errors are here that are causing my null array but if anyone could help i would greatly appreciate.

ucMedia
  • 2,500
  • 4
  • 21
  • 35
Pixelknight1398
  • 427
  • 1
  • 8
  • 26
  • 2
    Initialize the array first. `Square[] squares = new Square[100];` See http://stackoverflow.com/questions/1200621/declare-array-java – George Mulligan Jan 07 '16 at 00:47

2 Answers2

0

In your canvas class you will need to define the Squares array.

public MyCanvasView(Context context){
  squares = new Squares[100];
  super(context);
  for(int i = 0; i < 100; i++){
    squares[i] = new Square();
    squares[i].setIntervals();
  }
}
Pritam Banerjee
  • 15,297
  • 10
  • 71
  • 92
-1

You need to instantiate the array

public class MyCanvasView extends View {

Square[] squares = new Square[];

public MyCanvasView(Context context){
    super(context);
    for(int i = 0; i < 100; i++){
        squares[i] = new Square();
        squares[i].setIntervals();
    }
}
}