1

我是android开发的新手。作为一个更大项目的一部分,我想将数据从 android 设备插入到网络服务器。所以我做了一些研究和文章,比如来自 androidhive 的文章和来自 codeproject 的这篇文章对于尝试开发一个插入到远程 Web 服务器上的 mysql 数据库的测试应用程序非常有帮助。

这是我的安卓代码

ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()){
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://xxxxxxxx.in/installment.php");
        try{
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", editTextCustomer.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("amount", editTextAmount.getText().toString()));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            Log.i("postData", response.getStatusLine().toString());
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
         }
     }
    else { 
        Toast.makeText(PayBillActivity.this, "Internet Access, Denied!!", Toast.LENGTH_LONG).show();
    } 

这是php代码

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['amount'])) {

   $name = $_POST['name'];
   $amount = $_POST['amount'];

   $con=mysqli_connect("localhost","db_user","passwd","db_name");

    // Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO installment (name, amount) VALUES ('$_POST[name]','$_POST[amount]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

    // check if row inserted or not
    if ($sql) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Installment made successfully";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        echo $result;
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    //$amount = 1000;
    //echo $amount;
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

当我运行应用程序时,我得到了这个“NetworkOnMainThreadException”异常,因此没有添加任何行。但它与 HTML POST 完美结合。

谁能告诉我代码中的问题出在哪里?提前致谢!:)

4

2 回答 2

2

我想如果你花时间把这个问题发布到谷歌上,你可能会得到一些很好的答案......只是为了完成这个问题

有两个选项可供您选择,您可以添加一行代码并允许在主线程上进行网络操作,但这对您的应用程序和编码风格非常不利。

StrictMode.ThreadPolicy 策略 = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

更长的选择是重新设计代码以在单独的线程中执行网络操作。这对应用程序都有好处,您将学习如何处理多线程程序。

于 2013-09-08T16:32:46.480 回答
0

我认为你不应该使用那个严格或手动将它从 main..

只需使用一个智能的预制库,它就会为您做好一切!

下载: http: //loopj.com/android-async-http/

注意:这个库甚至使用 gzip 来压缩请求 :)

于 2013-09-08T17:39:41.773 回答