sarath
sarath

Reputation: 3201

adding textview values in asynchtask

Now i am doing an android application.In that application I am using asynchtask class to parse json data and i have to set that values in to ui.My program is like this.

class Activity
{
textview tv;
oncreate()
{
    setcontentview(layout);
    tv=(textview)findviewbyid(id);
    call to pageload()
}
class PageLoad extends AsyncTask<String, Void, Boolean>
{
    doInBackground()
    {
        json parsing
        tv.setText(data);
    }
}
}

But I couldn't set the value from pageload class.Please help me friends.

Upvotes: 0

Views: 1739

Answers (4)

MKJParekh
MKJParekh

Reputation: 34301

you can also use onProgressUpdate() of AsyncTask

You can call it using publishProgress(values) from your doInBackGround().

And set Text in your textbox in the onProgressUpdate().

Upvotes: 2

Graham Smith
Graham Smith

Reputation: 25757

You need to understand that doInBackground() runs on a different thread to the UI, therefore you cannot access the UI here. AsyncTask has two other methods:

  • onPreExecute() - before doInBackground() is run
  • onPostExecute() - after doInBackground() is run, can receive the result of the work done by doInBackground()

You need to pass the result of doInBackground() to onPostExecute() where you can then set the TextView's text.

I would suggest you read Google's article on how to use the Asynctask which can be found at http://developer.android.com/resources/articles/painless-threading.html and look at the class AsyncTask.

Example Code

private class MyAsynctask extends AsyncTask<String, Void, String> {

     protected String doInBackground(String... urls) {
         //do something heavy or resource intensive
         String data = resultOfSomeWork();
         return data;
     }

     protected void onPostExecute(String result) {
         myTextView.setText(result);
     }
 }

Upvotes: 2

user370305
user370305

Reputation: 109237

You can't use UI thread in doInBack..() of AsyncTask (As its only worker thread). Use onPostExecute() for it (If you want to make any ui related changes do in onPreExecute() or onPostExecuted()).

Just go through Android-AsyncTask and look at how it works.

Upvotes: 1

Ilya Gazman
Ilya Gazman

Reputation: 32226

You can't update UI from AsyncTask thread, it most be done on the main thread. You can use handler for this.

Upvotes: -2

Related Questions