我是安卓开发的新手。作为一个更大项目的一部分,我想将数据从安卓设备插入网络服务器。所以我做了一些研究和文章,比如来自androidhive的文章和来自codeproject的这篇文章,对于尝试开发一个插入到mysql数据库的测试应用程序非常有帮助,该数据库驻留在远程Web服务器上。
这是我的安卓代码
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完美配合。
谁能告诉我代码中的问题在哪里?提前感谢!:)
我想
如果你花时间把这个问题发布到谷歌上,你可能会得到一些很好的答案...... 只是为了完成这个问题
有两个选项可供您使用,您可以添加一行代码并允许在主线程上进行网络操作,但它对您的应用程序以及编码风格非常非常不利。
StrictMode.ThreadPolicypolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
更长的选项是重新设计代码,以便在单独的线程中执行网络操作。 这对应用程序都有好处,您将学习如何在多线程程序上工作。
我认为你不应该使用那么严格或手动将其从main中删除。
只需使用一个智能的预制库,它就会为你制作一切!
下载 : http://loopj.com/android-async-http/
注意:这个库甚至使用 gzip 来压缩请求:)