我是Android开发的新手。作为更大项目的一部分,我想将数据从Android设备插入到Web服务器。所以我做了一些研究,像The article from androidhive和this article from 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完美配合。
有谁能告诉我代码中的问题在哪里? 在此先感谢!:)
答案 0 :(得分:2)
我想如果你花了这些时间将这个问题发布到谷歌上,你可能会得到一些好的答案......只是为了完成这个问题
您可以使用两个选项,要么可以添加一行代码并允许在主线程上进行网络操作,但它对您的应用程序非常非常糟糕,也可以作为编码风格。
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()。permitAll()。build();
StrictMode.setThreadPolicy(策略);
更长的选择是重新设计代码以在单独的线程中执行网络操作。这对应用程序都有好处,您将学习如何使用多线程程序。
答案 1 :(得分:0)
我认为你不应该使用那个严格的,或者手动从主要的..
只需使用一个智能预制的lib,它就是为你制作一切!
下载:http://loopj.com/android-async-http/
注意:这个lib甚至使用gzip来压缩请求:)