1

我只是想知道这是否是在 android 中进行交流的好方法,还是有更安全、更好的方法?

  btnInsert.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) 
        {
            //Create the request
            **String url** = "http://10.0.2.2:80/practice/mysql_demo/inserting.php?";
            url = url + "txtName=" + txtName.getText().toString() + "&";
            url = url + "txtAge=" + txtAge.getText().toString() + "&";
            url = url + "txtAddress=" + txtAddress.getText().toString() + "&";
            url = url + "txtContact=" + txtContact.getText().toString() + "&";
            url = url + "txtOtherInformation=" + txtOtherInformation.getText().toString();

            **executeQuery(url)**;
            selectRecords(lstStudents);
        }
});
**public void executeQuery(String url)**
{
    //execute the URL, and get the result
    try
    {
        HttpClient http = new DefaultHttpClient();
        HttpGet http_get = new HttpGet(url);
        HttpResponse http_response = http.execute(http_get);
        HttpEntity http_entity = http_response.getEntity();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(http_entity.getContent()));
        String result = br.readLine();

        Toast.makeText(PHPDemo.this, result, Toast.LENGTH_LONG).show();
    }
    catch (Exception ex)
    {
        Toast.makeText(PHPDemo.this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}
4

2 回答 2

1

您必须使用threadorAsynctask进行网络相关操作。

 HttpResponse http_response = http.execute(http_get);  

Post Honeycomb 你会得到NetworkOnMainThreadException。使用AsyncTask或使用线程`。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

对于异步任务

http://developer.android.com/reference/android/os/AsyncTask.html

注意:您不能从后台线程更新 ui。您可以在 ui 线程上更新 ui。

于 2013-07-07T05:51:08.713 回答
0

@Raghunandan 是对的。除此之外,我建议单独对查询参数名称和值进行 URL 编码。您可以使用URLEncoder.encodewith"UTF-8"作为编码。

既然你问是否有更好的方法:

对于较新的 Android 版本,您可能需要考虑通过 Apache 的 HttpClient 使用 HttpUrlConnection 。

您可能还想查看一些Android 网络库,例如 Volley 或 OkHttp 等。

于 2013-07-07T18:06:29.863 回答