0

为什么运行此代码时模拟器会崩溃?

    TextView servmsg;
    String data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_msg);
        Vars();
        new SendtheData().execute("");
    }

    private void Vars() {
        // TODO Auto-generated method stub
        servmsg = (TextView) findViewById(R.id.tvServerMsg);
    }

    public class SendtheData extends AsyncTask<String, Integer, Void> {

        protected void onPreExecute(String f) {
            // called before doInBackground has started
            f = "f";
        }

        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(
                    "http://192.168.1.6/androidp2p/process.php");
            try {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
                pairs.add(new BasicNameValuePair("from", "test4"));
                pairs.add(new BasicNameValuePair("to", ""));
                pairs.add(new BasicNameValuePair("message", ""));
                post.setEntity(new UrlEncodedFormEntity(pairs));
                HttpResponse response = client.execute(post);
                // Convert the response into a String
                HttpEntity resEntity = response.getEntity();

                // Print the response
                data = EntityUtils.toString(resEntity);
                servmsg.setText(data);

                // Write the response to a log file
                if (resEntity != null) {
                    Log.i("RESPONSE", EntityUtils.toString(resEntity));
                }
            } catch (UnsupportedEncodingException uee) {
                uee.printStackTrace();
            } catch (ClientProtocolException cpe) {
                cpe.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            // called when the background task has made any progress
        }

        protected void onPostExecute() {
            // called after doInBackground has finished
        }

    }

但是当我注释掉这些行时:

// data = EntityUtils.toString(resEntity) // servmsg.setText(data)

它工作正常。如何获取服务器对 xml TextView 的响应?

另外,如果我可以添加的话,服务器的响应有 3 个字段,“to、from 和 message”。将这些中的每一个放入自己的 TextView 中的最佳方法是什么?

日志猫:

E/Trace(1584): error opening trace file: No such file or directory (2)
D/gralloc_goldfish(1584): Emulator without GPU emulation detected.
I/Choreographer(1584): Skipped 102 frames!  The application may be doing too much work on its main thread.
W/dalvikvm(1584): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
E/AndroidRuntime(1584): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(1584): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(1584): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(1584): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
E/AndroidRuntime(1584): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
E/AndroidRuntime(1584): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
E/AndroidRuntime(1584): at java.util.concurrent.FutureTask.run(FutureTask.java:137)

提前致谢。

在尝试受保护的 void onPostExecute() { // 在 doInBackground 完成后调用 servmsg.setText(data); }

这是新的 LogCat:

03-27 00:56:24.006: W/dalvikvm(1736): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
03-27 00:56:24.048: E/AndroidRuntime(1736): FATAL EXCEPTION: AsyncTask #1
03-27 00:56:24.048: E/AndroidRuntime(1736): java.lang.RuntimeException: An error occured while executing doInBackground()
03-27 00:56:24.048: E/AndroidRuntime(1736):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.lang.Thread.run(Thread.java:856)
03-27 00:56:24.048: E/AndroidRuntime(1736): Caused by: java.lang.IllegalStateException: Content has been consumed
03-27 00:56:24.048: E/AndroidRuntime(1736):     at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:100)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at org.apache.http.util.EntityUtils.toString(EntityUtils.java:112)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at com.project.keegan.testPrintMsg$SendtheData.doInBackground(testPrintMsg.java:77)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at com.project.keegan.testPrintMsg$SendtheData.doInBackground(testPrintMsg.java:1)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-27 00:56:24.048: E/AndroidRuntime(1736):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

这是我的 PHP 代码:

<?php

/* connect to database */
$db = mysql_connect("localhost", "root", "root");
if (!$db)
    die('could not connect');

mysql_select_db('androidp2p')
    or die("could not select database");


$from = mysql_real_escape_string($_POST['from']); 
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);


if ($_POST['to'])
{
    /* user wants to send a message */
    $query = "INSERT INTO messages (fromuser, touser, message) VALUES ('$from', '$to', '$message')";

    mysql_query($query)
        or die("\n\ndatabase error!\n". mysql_error());

    echo "ok. Messages have been saved.";

}
else
{
    /* user wants to retrieve his messages*/
    $query = "SELECT * FROM messages WHERE touser='$from'";

    $result = mysql_query($query)
        or die("\n\ndatabase error!\n". mysql_error());


    $message_count = mysql_num_rows($result);
    if( $message_count == 0)
    {
        /* no messages*/
        echo "ok. There are no messages.";  
    }
    else
    {
        /* output messages */
        while ($row = mysql_fetch_assoc($result))
        {
            echo "message start\n{$row['fromuser']}\n{$row['message']}\nmessage end\n";
        }


        /* clear messages */
        $query = "DELETE FROM messages WHERE touser='$from'";

        mysql_query($query)
            or die("\n\ndatabase error!\n". mysql_error());


        echo "ok. Cleared all messages.";       
    }
}


?>
4

1 回答 1

0
public class SendtheData extends AsyncTask<String, Integer, String> {

    protected void onPreExecute(String f) {
        // called before doInBackground has started
        f = "f";
    }

    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        String data = null;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://192.168.1.6/androidp2p/process.php");
        try {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
            pairs.add(new BasicNameValuePair("from", "test4"));
            pairs.add(new BasicNameValuePair("to", ""));
            pairs.add(new BasicNameValuePair("message", ""));
            post.setEntity(new UrlEncodedFormEntity(pairs));
            HttpResponse response = client.execute(post);
            // Convert the response into a String
            HttpEntity resEntity = response.getEntity();

            // Print the response
            data = EntityUtils.toString(resEntity);

            // Write the response to a log file
            if (resEntity != null) {
                Log.i("RESPONSE", EntityUtils.toString(resEntity));
            }
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        } catch (ClientProtocolException cpe) {
            cpe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return data;
    }

    protected void onProgressUpdate(Integer... progress) {
        // called when the background task has made any progress
    }

    protected void onPostExecute(String data) {
        if(null != data)
        {
            servmsg.setText(data);
        }else{
            //handle Error
        }

    }

}

您可以像这样更改您的AsyncTask, 实施。总是onPsotExecuteAsyncTask. 希望这会有所帮助。

另外,如果我可以添加的话,服务器的响应有 3 个字段,“to、from 和 message”。将这些中的每一个放入自己的 TextView 中的最佳方法是什么?

您从 PHP 页面返回的响应,您可以将其设为JSON响应并从客户端JSON使用 android 解析该响应JSONParser,您的响应可能如下所示"{status:'200',statusMessage:'success or as you wish',data{to:'value',from:'value',message:'your message'}}"

于 2013-03-27T05:17:16.783 回答