0

我正在为学校编写一个非常简单的游戏,但需要使用 asynctask。我正在使用 ADT (Eclipse)。以下是相关代码:

 public void oklog(View view) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, URISyntaxException, ClientProtocolException, IOException, IllegalStateException, SAXException {

    new log_async().execute();
}

String DocumentToString(Document doc) throws TransformerConfigurationException, TransformerException{
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString();//.replaceAll("\n|\r", "");

    return output;
}
class log_async extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){

        TextView tv1 = (TextView) findViewById(R.id.textView3);
        tv1.setText("Pracuję...");

    }

    @Override
    protected String doInBackground(String...voids ) {

        TextView tv1 = (TextView) findViewById(R.id.textView3);
        tv1.setText("haha");
        String a = "";
        try {
            tv1.setText("haha2");

        HttpClient client = new DefaultHttpClient();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder docBuilder = null;
        docBuilder = factory.newDocumentBuilder();
        tv1.setText("haha3");
        Document doc = docBuilder.newDocument();

        Element env = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soap:Envelope");
        Element body = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soap:Body");
        Element zaloguj = doc.createElementNS("http://tempuri.org/", "tc:Zaloguj");
        zaloguj.appendChild(doc.createElementNS("http://tempuri.org/", "tc:login"));
        zaloguj.appendChild(doc.createElementNS("http://tempuri.org/", "tc:pass"));

        EditText et1 = (EditText)findViewById(R.id.editText1);
        zaloguj.getElementsByTagNameNS("http://tempuri.org/", "login").item(0).setTextContent(et1.getText().toString());
        EditText et2 = (EditText)findViewById(R.id.editText2);
        zaloguj.getElementsByTagNameNS("http://tempuri.org/", "pass").item(0).setTextContent(et2.getText().toString());

        tv1.setText("haha4");
        body.appendChild(zaloguj);
        env.appendChild(body);
        doc.appendChild(env);

        String s = null;
        s = DocumentToString(doc);

        Log.i("SOAP", s);

        StringEntity entity = null;

        entity = new StringEntity(s);
        HttpPost post = null;
        post = new HttpPost(new URI("http://www.kdkade.somee.com/oldschoolrpg_main.asmx"));
        tv1.setText("haha5");
        post.addHeader("SOAPAction", "http://tempuri.org/Zaloguj");
        post.addHeader("Content-Type", "text/xml; charset=utf-8");

        post.setEntity(entity);
        HttpResponse response = null;
        response = client.execute(post);
        Document responseDoc = null;

        responseDoc = docBuilder.parse(response.getEntity().getContent());

        tv1.setText("haha6");
        s = DocumentToString(responseDoc);

        Log.i("RESPONSE", s);

        //TextView tv1 = (TextView) findViewById(R.id.textView3);
        String[] temp1 = s.split("<ZalogujResult>");
        String[] temp2 = temp1[1].split("</");
        tv1.setText(temp2[0]);
        a = temp2[0];
        //tv1.setText(responseDoc.getElementsByTagNameNS("http://tempuri.org/","ZalogujResult").toString());
        //tv1.setText(s);
        //return null;
        //return null;
        }
        catch (Exception e){
            tv1.setText(e.getMessage());
        }
        tv1.setText("wtf");
        return a;
    }

    //protected void onProgressUpdate(Integer... progress) {
        //setProgressPercent(progress[0]);
    //}

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

doinbackground 里面的代码之前在 oklog 方法中,它工作正常。如您所见,我在这里和那里放置了一些 TextView 文本更改,以在模拟器上查看它的进展情况,有时它只是 "Pracuję..." (OnPreExecute 中的那个),有时甚至会变成 "haha5" 和有时应用程序崩溃(似乎相当随机)。不幸的是,我失去了这里的问题。谁能告诉我错误在哪里还是模拟器问题?

4

2 回答 2

1

您正在尝试在后台线程上更新 UI。您应该在主 ui 线程上更新 ui。doInbackground()执行完成后立即在后台线程上调用onPreExecute()。此步骤用于执行可能需要很长时间的后台计算。用于runOnUiThread()更新doInBackground().

onProgressUpdate(Progress...)在 UI 线程上调用。它可用于动画进度条或在文本字段中显示日志。您也可以使用它。

但我建议你在onPostExecute(param). 的结果doInBackground()是一个参数onPostExecute(param)onPostExecute(param)在 UI 线程上调用。

你也可以初始化你的 textviewonCreate()并使用它。

您可以查看 The 4 steps @ http://developer.android.com/reference/android/os/AsyncTask.html下的主题

runOnUiThread(new Runnable(){

@Override
public void run(){

// update ui here

}
});
于 2013-05-26T18:34:11.057 回答
1

如上面的答案所述,您正在从非 UI 线程(即,log_async正在运行的后台线程)更新 UI。

在方法中传达进度的一个选项doInBackground()是使用publishProgress(),这反过来会导致onProgressUpdate()随后调用 。

您还需要覆盖onProgressUpdate()以适当地更新 UI。

于 2013-05-26T19:06:52.403 回答