【问题标题】:Using AsyncTask and returning values to the UI main thread使用 AsyncTask 并将值返回给 UI 主线程
【发布时间】:2012-08-23 04:47:08
【问题描述】:

我有一个 Android 活动来显示 Web 服务的输出。我在另一个扩展 AsyncTask 的私有类中调用了 Web 服务,并希望向主 UI 线程返回一个值。

这是我的活动。

public class CallCalcService extends Activity {

private String METHOD_NAME = "sum"; // our webservice method name
private String NAMESPACE = "http://backend.android.web.org"; 

private String SOAP_ACTION = NAMESPACE + METHOD_NAME; 

private static final String URL = "http://192.168.1.14:8080/AndroidBackend1/services/Calculate?wsdl"; 

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_call_calc_service);

    //TextView tv = (TextView) findViewById(R.id.textView1);
    //Object res=new HardWorkThread().execute();
    //tv.setText("Addition : "+ res.toString());

    new HardWorkThread()
    {
        public void onPostExecute(String result)
        {
            TextView txt = (TextView) findViewById(R.id.textView1);
            txt.setText("Addition : "+result);
        }
    }.execute("");



}

private class HardWorkThread extends AsyncTask{

    @Override
    protected String doInBackground(Object... params) {
        // TODO Auto-generated method stub
        String result=null;
        try {
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
            request.addProperty("i", 5);
            request.addProperty("j", 15);
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            androidHttpTransport.call(SOAP_ACTION,envelope);

             result = envelope.getResponse().toString();
            System.out.println("Result : " + result);
            //((TextView) findViewById(R.id.textView1)).setText("Addition : "+ result.toString());
        } catch (Exception E) {
            E.printStackTrace();
            //((TextView) findViewById(R.id.textView1)).setText("ERROR:"
                //  + E.getClass().getName() + ":" + E.getMessage());
        }
        return result;
    }



}

}

我想要做的是将 String 结果值返回到主 UI,以便我可以将该值设置到 textview。

String result;

TextView tv=findViewById(R.id.textView1);
tv.setText(result);

我该怎么做?

【问题讨论】:

    标签: java android-asynctask


    【解决方案1】:

    你应该Override onPostExecute() 方法。

    类似这样的:

            @Override
        protected void onPostExecute(String result) {
            TextView tv = findViewById(R.id.textView1);
            tv.setText(result);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 2018-06-10
      • 2015-03-17
      • 2011-05-10
      • 2011-03-22
      相关资源
      最近更新 更多