skip to Main Content

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

2

Answers


  1. Check for any possible exception such as NullPointerException thrown. Check the error logs.

    Login or Signup to reply.
  2. 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); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search