开发者

set component value in thread android

i want to change a component value in thread. we did it at c# with invoke. how could do i do it in android?

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class procActivity extends Activity {
    /** Called when the activity is first created. */
    String H ="";

    EditText et;

    public void onCreate(Bundle savedInstanceState)  
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);

        et = (EditText) findViewById(R.id.etDetail);

        String result = "";

        et.setText(
                "             Process Manager :         \n"
            +   "****************************\n"
            +   "PID      Name      Process Usage    \n"
            +   result
                );

        showResult sohwresult = new showResult();
        sohwresult = (showResult) new showResult().execute("");

    }

        class showResult extends AsyncTask<String, Integer, String> 
        {
        // Called to initiate the background activity
        @Override
        protected String doInBackground(String... statuses) 
    开发者_开发技巧    { 
        while(true)
          try 
          {
            String result1 = "";

            H=(
                    "             Process Manager :         \n"
                +   "****************************\n"
                +   "PID      Name      Process Usage    \n"
                +   result1
                    );
       ******               et.setText(H); //// it s where i want to do it!************

          } 
          catch (Exception e) 
          {
              break;
          }
            return "";
        }

        // Called when there's a status to be updated
        @Override
        protected void onProgressUpdate(Integer... values) 
        { 
          super.onProgressUpdate(values);
        }

        // Called once the background activity has completed
        @Override
        protected void onPostExecute(String result) 
        { 

        }
    }
}


You cannot change UI from non-UI threads. In your case your can:

protected String doInBackground(String... statuses) 
{
    //... 
    H = ...;
    return H;
}

@Override
protected void onPostExecute(String result) 
{ 
   et.setText(H);
}

That's because onPostExecute will be called in UI-thread and therefore it can change state of UI components. For more details see AsyncTask documentation.


  1. inazaruk's answer
  2. Activity.runOnUiThread(Runnable action)
  3. new Handler(Context.getMainLooper()).post(Runnable action), where the context main looper is the queue you want to run your code on.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜