Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 1.40 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to update the text in the UI from the background thread in Android
  2. public class DefaultActivity extends Activity{
  3.  
  4.   TextView textView;
  5.   public void onCreate(Bundle savedInstanceState){
  6.     super.onCreate(savedInstanceState);
  7.     setContentView(R.layout.main);
  8.     textView=(TextView)findViewById(R.id.textId);
  9.     new networkFileAccess().execute("background","Progress","result");
  10.   }
  11.  
  12.   private class networkFileAccess extends AsyncTask<String,String,String>{
  13.  
  14.     protected String doInBackground(String... background){
  15.        return changeText();
  16.     }
  17.  
  18.     private String changeText(){
  19.      //Code to Access data from the Network.
  20.      //Parsing the data.
  21.      //Retrieving the boolean Value.
  22.      if(booleanistrue){
  23.       //Displaying some text on the UI.
  24.       publishProgress("someTextOnUI");
  25.       //Send request till we get get boolean value as false.
  26.       changeText();
  27.      }else{
  28.        return "success";
  29.      }
  30.       return "";
  31.     }
  32.  
  33.     protected void onProgressUpdate(String... progress){
  34.       textView.setText("Wait background work is going on");
  35.     }
  36.  
  37.     protected void onPostExecute(String result){
  38.       if(result.equals("success")){
  39.        //Code to finish the activity.
  40.       }
  41.     }
  42.   }
  43.        
  44. Thanks&Regards,
  45. Venkat.
  46.        
  47. runOnUiThread(new Runnable() {
  48. public void run() {
  49.     tv.setText("ABC");
  50. }
  51.  });
  52.        
  53. runOnUiThread(new Runnable() {
  54.     public void run() {
  55.         // change text
  56.     }
  57. });