如何从Android中的后台线程更新UI中的文本

use*_*614 0 android android-asynctask

在我的应用程序中,我需要根据来自网络的数据更新UI中的文本.因为我AsyncTask在Android中使用后台工作.我的代码如下.

public class DefaultActivity extends Activity{

  TextView textView;
  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView=(TextView)findViewById(R.id.textId);
    new networkFileAccess().execute("background","Progress","result");
  }

  private class networkFileAccess extends AsyncTask<String,String,String>{

    protected String doInBackground(String... background){
       return changeText();
    }

    private String changeText(){
     //Code to Access data from the Network.
     //Parsing the data.
     //Retrieving the boolean Value.
     if(booleanistrue){
      //Displaying some text on the UI.
      publishProgress("someTextOnUI");
      //Send request till we get get boolean value as false.
      changeText();
     }else{
       return "success";
     }
      return "";
    }

    protected void onProgressUpdate(String... progress){
      textView.setText("Wait background work is going on");
    }

    protected void onPostExecute(String result){
      if(result.equals("success")){
       //Code to finish the activity.
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

}

在上面的代码中,我能够运行后台线程,直到我得到布尔值为false.但是文本没有在UI上更新.我可以onProgressUpdate通过调用publishProgressmethod 更新UI上的文本.使用()方法.任何suggesstions.

Sha*_*mam 10

把你的Ui方法放在runonUiTHREAD中就像这样

runOnUiThread(new Runnable() {
public void run() {
    tv.setText("ABC");
}
 });
Run Code Online (Sandbox Code Playgroud)


Vee*_*eer 7

在AsyncTask中,onPostExecute()和onPreExecute()都在UI线程上运行.因此,您可以更改onPostExecute()方法中的文本.

或者你也可以在线程中运行的doInBackground()方法中调用runOnUiThread:

runOnUiThread(new Runnable() {
    public void run() {
        // change text
    }
});
Run Code Online (Sandbox Code Playgroud)

它可以运行在UI线程上运行.