I am making a checkers game and the following code causes an application not responding dialog when in operation. How can i make the code efficient and remove the Anr dialog.
public void drawPawns() {
for(int i=0; i<playableTileView.length; i ) {
if(playableTile[i].getIsTaken() == 1) playableTileView[i].setBackgroundResource(R.drawable.white_pawn);
else if(playableTile[i].getIsTaken() == -1) playableTileView[i].setBackgroundResource(R.drawable.brown_pawn);
else if(playableTile[i].getIsTaken() == 2) playableTileView[i].setBackgroundResource(R.drawable.white_queen);
else if(playableTile[i].getIsTaken() == -2) playableTileView[i].setBackgroundResource(R.drawable.brown_queen);
else playableTileView[i].setBackgroundResource(0);
}
CodePudding user response:
Check for any possible exception such as NullPointerException thrown. Check the error logs.
CodePudding user response:
How many playableTileView are there? If it is more than 5 then You need to use handler as setBackground is a UI heavy operation also you can't use it background thread here. Also you can check and store the previous set background and set only when it is required.
I am assuming you have added proper drawable for all image-resolution specially hdpi, xhdpi and xxhdpi
handler.postDelayed(()->{
if(playableTile[i].getIsTaken() == 1) playableTileView[i].setBackgroundResource(R.drawable.white_pawn);
else if(playableTile[i].getIsTaken() == -1) playableTileView[i].setBackgroundResource(R.drawable.brown_pawn);
else if(playableTile[i].getIsTaken() == 2) playableTileView[i].setBackgroundResource(R.drawable.white_queen);
else if(playableTile[i].getIsTaken() == -2) playableTileView[i].setBackgroundResource(R.drawable.brown_queen);
else playableTileView[i].setBackgroundResource(0);
},10);