Issue
I am creating a class to use in an android app. It should keep track of a grid of "tiles", which can change colors. but it keeps crashing when the "checkTile" method that I created is called. That method simply runs through some if statements to see if any of the surrounding tiles are "blank", then calls the "switchTile" command on any blank tiles, which swaps the drawables of two imageviews.
The logcat says: 3474-3474/? E/VCD: init_modem : Fail to open /dev/umts_atc0, errno = 2
Here is the class:
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
import java.util.Random;
public class TileBoard {
private Drawable[][] tiles;
private Drawable blank;
public TileBoard(int width, int height, Drawable blank) {
tiles = new Drawable[width][height];
this.blank = blank;
}
public void switchTiles(int tile1X, int tile1Y, int tile2X, int tile2Y) {
Drawable placeholder = tiles[tile1X][tile1Y];
tiles[tile1X][tile1Y] = tiles[tile2X][tile2Y];
tiles[tile2X][tile2Y] = placeholder;
}
public void checkTile(int tileX, int tileY) {
if (tileX != 0) if (tiles[tileX - 1][tileY].equals(blank))
switchTiles(tileX, tileY, tileX - 1, tileY);
if (tileY != 0) if (tiles[tileX][tileY - 1].equals(blank))
switchTiles(tileX, tileY, tileX, tileY - 1);
if (tileX != tiles[0].length) if (tiles[tileX + 1][tileY].equals(blank))
switchTiles(tileX, tileY, tileX + 1, tileY);
if (tileY != tiles.length) if (tiles[tileX][tileY + 1].equals(blank))
switchTiles(tileX, tileY, tileX, tileY + 1);
}
public void scrambleBoard() {
Random rand = new Random();
for (int i = 0; i < tiles[0].length; i++) {
for (int j = 0; j < tiles.length; j++) {
int randomPositionX = rand.nextInt(tiles[0].length);
int randomPositionY = rand.nextInt(tiles.length);
switchTiles(i, j, randomPositionX, randomPositionY);
}
}
}
public void setBoard(ArrayList<Drawable> images) {
for (int i = 0; i < tiles.length * 5; i += 5) {
for (int j = 0; j < tiles[0].length; j++) {
tiles[j][i / 5] = images.get(i + j);
}
}
}
}
Solution
The problem has been solved. There were two things wrong. First of all, in some of the if statements in checkTile needed to have the condition tileY != tiles.length - 1
instead of tileY != tiles.length
. The lack of the -1 was causing a ArrayIndexOutOfBoundsException
. Second, I was trying to compare drawables with the .equals
command, which apparently doesn't work on drawables.
Thank you to @Md. Asaduzzaman, who pointed out the ArrayIndexOutOfBoundsException
Answered By - Sebastian Nuxoll
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.