Android在AsyncTask中从processFinish返回值

时间:2014-09-10 08:46:18

标签: android android-asynctask

在下面这段代码中,我希望从processFinish方法传递数据,以便在外部类中使用,但我无法修复问题而且我无法在processFinish函数中从call返回值

public class WSDLHelper  implements AsyncResponse{
    public SoapObject request;

    private String MainResult;

    public String call(SoapObject rq){

        new ProcessTask(rq, this).execute();
        return MainResult;
    }

    @Override
    public void processFinish(String output) {
        MainResult = output;
    }
}

class ProcessTask extends AsyncTask<Void, Void,  String> {
    public AsyncResponse delegate=null;

    SoapObject req1;

    public ProcessTask(SoapObject rq, AsyncResponse delegate) {
        req1 = rq;
        this.delegate = delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(this.req1);

        AndroidHttpTransport transport = new AndroidHttpTransport(Strings.URL_TSMS);
        transport.debug = true;

        String result = null;
        try {
            transport.call(Strings.URL_TSMS + this.req1.getName(), envelope);
            result = envelope.getResponse().toString();
        } catch (IOException ex) {
            Log.e("" , ex.getMessage());
        } catch (XmlPullParserException ex) {
            Log.e("" , ex.getMessage());
        }

        if (result.equals(String.valueOf(Integers.CODE_USER_PASS_FALSE))) {
            try {
                throw new TException(PublicErrorList.USERNAME_PASSWORD_ERROR);
            } catch (TException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    protected void onPostExecute(String result) {
        delegate.processFinish(result);
    }
}

请帮我开发call方法,将output值返回给外部课程。感谢

2 个答案:

答案 0 :(得分:0)

您正在实施AsyncResponce。 所以 取代

new ProcessTask(rq, new AsyncResponse() {
            @Override
            public void processFinish(String output) {
                MainResult = output;
            }
        }).execute();

通过

new ProcessTask(rq, this).execute();

然后,您的课程overrided方法p rocessFinish(String output)将会致电。

并在processFinish()中使用您的值,而不是使用call()方法重新调整值。

答案 1 :(得分:0)

ProcessTask是一个异步任务,所以当你调用call方法时,你会在null时获得return MainResult,因为它还没有被processFinish方法设置。