user5162677
user5162677

Reputation:

How do I modify a TextView of MainActivity from an AsyncTask?

I'm writing a chat application, which has 2 processes (Get and Send). They are written inside MainActivity and work like this:

Send: //Called when button is pressed
(1) Get String from editText into MSG
(2) Run AsyncTask_SEND(MSG).executeOnExecutor(...) to send
    (this procedure avoids internet calls at main thread (NetworkOnMainThreadException))
(3) TextView.setText( TextView.getText() + "Local : " + MSG + "\n" );


Get: //Called at onCreate
Run AsyncTask_GET().executeOnExecutor(...) to get messages.
It's doInBackground works like this:
|    (1) Declare String MSG
|    (2) While client still has messages to send (kind of infinite loop):
|    |    (2.1) Get client's next line into MSG
|    |    (2.2) TextView.setText( TextView.getText() + "Remote : " + MSG + "\n" );

The problem is step (2.2) from Get obviously doesn't work.

Instead of it, I'm using Log.d("Remote", MSG) to print remote messages at LogCat console.

My question is: Given this TextView is placed at MainActivity (and the AsyncTask_GET is an independent class), how do I modify this TextView from the AsyncTask_GET ?

Upvotes: 0

Views: 394

Answers (2)

SaNtoRiaN
SaNtoRiaN

Reputation: 2202

If it's independant class, you can add a constructor to your AsyncTask class and send a TextView to it, then you can change its text in onPostExecute() method like:

public class GetMsg extends AsyncTask<Void, Void, Void> {
    private TextView msg;

    public GetMsg(TextView msg){
        this.msg = msg;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Change the text of msg TextView
        msg.setText("Add your text here");
}

and to call this you just add your TextView inside the constructor like

TextView tv = (TextView) findViewById(R.id.textview); // your textview
new GetMsg(tv).execute();

Upvotes: 3

Adam Fręśko
Adam Fręśko

Reputation: 1064

Async task got buildin method just for that. Its called onProgressUpdate, adn it runs on ui thread.

private class DownloadFilesTask extends AsyncTask<URL, String, Long> {
     protected Long doInBackground(URL... urls) {

             publishProgress("hello from async task"); 
            // you call it just like this, but remember its array

         }
         return totalSize;
     }

     protected void onProgressUpdate(String... string) {

      textView.settext(string[0]); // and here you set the text

     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Upvotes: 0

Related Questions