Mahoni
Mahoni

Reputation: 7466

Update UI multiple times during Activity method

In my main activity I have a method linked to a button, when the button is pressed it should be disabled, then a HTTP request is made and after the method finishes the button should be enabled again.

public void onClick(View view) {        
    Button button = (Button) findViewById(R.id.my_button);
    button.setEnabled(false);
        button.setTextColor(Color.GRAY);
    try {
        // make HTTP request
    } catch (IOException e) {
        // error
    } finally {
        button.setEnabled(true);
        button.setTextColor(Color.GRAY);
    }
}

So normally the button should change color after I clicked it, then I wait for the request to happen which will timeout, hence I wait for 3 seconds, and then the button's color should change back.

Unfortunately the color/button is not updated once, until the method finishes. What is the reason for that? How is it done properly?

Upvotes: 0

Views: 91

Answers (1)

Alécio Carvalho
Alécio Carvalho

Reputation: 13647

Use the AsyncTask to make the HTTP call (place it in the method: doInBackground() ) and put the code to re-enable the button again on the method onPostExecute().

Upvotes: 3

Related Questions