Android Asynctask无法完成

时间:2013-05-26 18:26:59

标签: java android eclipse android-asynctask adt

我正在为学校写一个非常简单的游戏,但是需要使用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”和有时应用程序崩溃(似乎相当随机)。不幸的是,我在这里失去了什么错。谁能告诉我哪里出错或是模拟器问题?

2 个答案:

答案 0 :(得分:1)

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

在UI线程上调用

onProgressUpdate(Progress...)。它可用于为进度条设置动画或在文本字段中显示日志。你也可以使用它。

但我建议您更新onPostExecute(param)中的用户界面。 doInBackground()的结果是onPostExecute(param)的参数。在UI线程上调用onPostExecute(param)

您也可以在onCreate()中初始化一次textview并使用相同的文本视图。

您可以查看“http://developer.android.com/reference/android/os/AsyncTask.html

的4个步骤”下的主题
runOnUiThread(new Runnable(){

@Override
public void run(){

// update ui here

}
});

答案 1 :(得分:1)

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

doInBackground()方法中传达进度的选项是使用publishProgress(),这将导致随后调用onProgressUpdate()

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