php - 从android应用程序插入到mysql

标签 php android mysql

我是安卓开发的新手。作为一个更大项目的一部分,我想将数据从 android 设备插入到 web 服务器。所以我做了一些研究和文章,比如 The article from androidhivethis 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 完美配合。

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

最佳答案

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

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

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(政策);

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

关于php - 从android应用程序插入到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18685160/

相关文章:

java - 如何以编程方式退出 Android 应用程序?

android - Activity 过渡黑屏

PHP 是 MySQL DATETIME 字段 14 天前从今天算起

MySQL插入问题

php - 在 PHP 中向 REST API 发送 JSON POST 请求

php - Laravel Carbon 日期 diffInDays() 字符串错误

php - 有没有办法从 PHP 代码加载的文件中解析 PHP?

php - mysqli_query 不再插入数据

java - Android - 如何以编程方式截取屏幕截图

mysql - 如何解决 'where clause' 许多子句中的未知列