Question

Continuously changing imageview image on start of activity. Will it be possible without using Thread?if not at least tell me how to use Thread properly and how should I initiate it. Please.,

It's for a whack a mole like android game.


I tried to do simple display of random text but did not work.

public class NewGame extends Activity {

    gameThread gameOn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newgame);

        hView = (TextView) findViewById(R.id.HammersText);
        gameOn = new gameThread();
        gameOn.start();
    }
}

public class gameThread extends Thread
{
    NewGame gameOn;

    public void run() {
        super.run();

        Random ramhole = new Random();
        int hole = ramhole.nextInt(8);

        Random ramletter = new Random();
        int letter = ramletter.nextInt(26);

        gameOn = new NewGame();

        gameOn.hView.setText("Hole = "+hole+"Letter = "+letter);
    }

}

Please help me out on this.

Was it helpful?

Solution

Use a countdownTimer instead of Thread

new CountDownTimer(9000000, 5000) {

 public void onTick(long millisUntilFinished) {
       Random ramhole = new Random();
        int hole = ramhole.nextInt(8);

        Random ramletter = new Random();
        int letter = ramletter.nextInt(26);
        hView.setText("Hole = "+hole+"Letter = "+letter);
 }

 public void onFinish() {
   //Restart timer if you want.
 }
}.start();

You can still do with Threading but its a overkill for what you are trying to do. Also in your case, you cannot do

gameOn = new NewGame();  

Activity always needs to be initialized by framework. And setText api should always be called from Ui thread. Maybe that is why your app is not working

OTHER TIPS

You should only be touching the UI on the main UI thread, so if you do decide to use threads, then you should look at the AsyncTask.

If it was my game, I would start a new AsyncTask for each hole. In doInBackground it would sleep for some random amount of time, then it would publish progress. In every even onProgressUpdate it would show the mole. In every odd onProgressUpdate it would hide the mole (if it hasn't been whacked.) By handling the show/hide in onProgressUpdate you are automatically on the main UI thread so no worries there, and having a separate thread for each hole will allow you to have a more dynamic playing field of holes/moles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top