【问题标题】:How to add an android object into a MySql Database如何将 android 对象添加到 MySql 数据库中
【发布时间】:2016-03-12 12:09:23
【问题描述】:

我尝试使用 JSON 在我的外部数据库中添加一个对象。我到达是从数据库中获取数据,带有输入流,但我无法添加数据。

也许我在我的 Android 活动或我的 PHP 代码中犯了一个错误。当我按下添加按钮时,android 活动关闭并显示主要活动,并且我的数据库中没有新的对象。

我在网上搜索过,但很多教程都使用了已弃用的资源。

我在按下按钮时执行“doInBackground”函数。

我只想使用 java 或 android 本机代码,不想修改我的 graddle 脚本。

我的数据库只包含一个带有城镇名称和主键的表。

我的java代码:

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewTown extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AddTownActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         */
        protected String doInBackground(String... args) {

            JSONObject jsonObject = new JSONObject();

            try {
                URL url = new URL("http://192.168.0.10/T1/create_town.php");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(10000);
                connection.setConnectTimeout(15000);
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);

                jsonObject.put("name", name);
                String jsonString = jsonObject.toString();

                Log.i("doInBackground", jsonString);

                OutputStream outputStream = connection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                writer.write(jsonString);
                writer.flush();
                writer.close();

                outputStream.close();
                connection.connect();

            } catch (IOException e) {
                Log.i("doInBackground", e.getMessage());
            }catch (JSONException e){
                Log.i("doInBackground", e.getMessage());
            }

            // check log cat fro response
            Log.d("Create Response", jsonObject.toString());

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            try {
                int success = jsonObject.getInt(TAG_SUCCESS);

                Log.i("onPostExecute", "success :"+String.valueOf(success));

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);
                    // closing this screen
                    finish();
                }else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            pDialog.dismiss();
        }
        }
}

我的 PHP 代码:

<?php 
    if(isset($_POST['name'])){
        $name = $_POST['name'];
        // on se connecte à notre base  pour recuperer les data
        $mysqli = new mysqli('localhost', 'root', '',"db_ville"); 
        /* Vérification de la connexion */
        if ($mysqli->connect_errno) {
            printf("Échec de la connexion : %s\n", $mysqli->connect_error);
            exit();
        }
        $result = $mysqli->query("INSERT INTO liste_villes(name) VALUES ('$name')");
        // check if row inserted or not
        if ($result) {
            // successfully inserted into database
            $response["success"] = 1;
            $response["message"] = "Product successfully created.";
            // echoing JSON response
            echo json_encode($response);
        } else {
            // failed to insert row
            $response["success"] = 0;
            $response["message"] = "Oops! An error occurred.";
            echo json_encode($response);
        }
        $result->close();
        $mysqli->close();
    }
    else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";
        echo json_encode($response);
    }
?>

【问题讨论】:

  • 请将标题改成简短、清晰的问题。
  • 1- 将 android 代码中的 localhost 更改为服务器的 IP 地址或主机名/域名,2- 您的插入语句看起来不完整,您缺少必须使用的 VALUES ... 部分$name变量
  • 刚刚注意到(null,name)关于第2点,如果你是直接插入而不先列出字段,你可能需要写成...(null,'$name')"
  • 我已经按照你说的修改了php代码。我在本地网络上工作。我的服务器不在线,但它可以工作。我可以ping它或访问网页。
  • 不是本地网络或网络问题,localhost127.0.0.1 表示本机,所以当你运行android app 时,localhost 会指手机,好像您的手机上安装了 apache、mysql ...等,但事实并非如此。这就是为什么您需要在 android 代码 中使用服务器的 IP 地址(例如 192.168.1.10)

标签: java php android mysql json


【解决方案1】:

您已经在 android Async 任务中创建了 jsonObject.put("username", name);,并且您尝试使用 $name = $_POST['name'] 获取 PHP 代码中的数据。 请将其更改为$name = $_POST['username']。 我认为是这个问题,请检查,谢谢

【讨论】:

  • 我已经进行了修改,但我有两个 android 运行时 1 - RuntimeException:执行 doInBackground() 和 2 - RuntimeException:无法在未调用 Looper.prepare 的线程内创建处理程序()。我使用了带有 http 地址的 httpsURLConnection 类。
  • 此错误是由于来自异步任务的 doInBackground() 方法的意图调用。请仅从异步任务的 onPostExecute() 方法更新 UI。
猜你喜欢
  • 1970-01-01
  • 2020-11-15
  • 2014-10-16
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
相关资源
最近更新 更多