如何使用EntityUtils将服务器响应写入TextView?

时间:2013-03-27 04:31:39

标签: android textview

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

    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”。将每个文件放入自己的TextViews的最佳方法是什么?

logcat的:

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)

提前致谢。

尝试后         protected void onPostExecute(){             //在doInBackground完成后调用             servmsg.setText(数据);         }

这是新的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.";       
    }
}


?>

1 个答案:

答案 0 :(得分: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,实施。始终使用onPsotExecute的{​​{1}}方法处理结果。希望这会有所帮助。

  

另外如果我可以添加,服务器的响应有3个字段,   “来自,来自和消息”。将这些中的每一个放入的最佳方法是什么?   他们自己的TextViews?

您从PHP页面返回的响应,您可以将其设为AsyncTask响应,并从客户端使用android JSON解析JSON响应,您的响应可能如下所示JSONParser