IIRed-DeathII
IIRed-DeathII

Reputation: 1157

how to update views with two concurrent threads Android

I have Character and a Monster, and want to simule a battle. To do so, I created two threads, one with the character's attack, and another with the monster's attack. Character and monster has different attack speed, so their threads "wait" time will be different. My method looks like this (I summed up the method):

public void attack(){

//Character's attack thread
Thread characterAttackThread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            while(character.getHp()>0 && monster.getHp()>0){
                int damage = character.getDamage();
                monster.setHp(monster.getHp() - damage);
                Thread.sleep(character.getSpeed());
            }
            if(character.getHp()<=0){
                updateScreen("Character died"); //shows message to user
            }else{
                updateScreen("Monster died"); //shows message to user
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

//Monster's attack thread
Thread monsterAttackThread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            while(character.getHp()>0 && monster.getHp()>0){
                int damage = character.getDamage();
                monster.setHp(monster.getHp() - damage);
                this.wait(character.getSpeed());
            }
            Thread.sleep(monster.getSpeed());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

characterAttackThread.start();
monsterAttackThread.start();
}

But when I reach the updateScreen("Message"); I get the error

Only the original thread that created a view hierarchy can touch its views.

What can I do to get the problem solved?

Thanks in advance!

Upvotes: 0

Views: 719

Answers (1)

Sushil
Sushil

Reputation: 8478

You cannot modify the android toolkit from any other thread apart from UI thread

This link will give you clarifications :

http://developer.android.com/guide/components/processes-and-threads.html

You may do one of the follow:

  1. Use AsyncTask and update UI from onPostUpdate() function
  2. Write a handler in UI thread and postmessage to it from your thread
  3. Use the following code in your thread:

    MainActivity.this.runOnUiThread(new Runnable() {
    

    public void run() {

        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    
    }
    

    });

Hope this helps

Upvotes: 1

Related Questions