Question

in my android application i have created Background thread to load data from the internet into my app.In that background thread i have set some values to text fields as followings.

protected Void doInBackground(Void... params) {

if(!isDataFromInternetAvailable){
  re=(TextView)findViewById(android.R.id.empty);
  re.setText("no data ");
}
else{
re=(TextView)findViewById(android.R.id.empty);
  re.setText("You have data ");
}

return null;

}

but it will give following exception.

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

how can i fix this??

Was it helpful?

Solution

Change your AsyncTask to return a String. In onPostExecute, update the text view with the String result.

protected String doInBackground(Void... params) {
    return isDataFromInternetAvailable
        ? "You have data "
        : "no data ";
}

protected void onPostExecute(String result) {
    re = (TextView) findViewById(android.R.id.empty);
    re.setText(result);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top