如何将android对象添加到MySql数据库中

时间:2016-03-12 12:09:24

标签: java php android mysql json

我尝试使用JSON在外部数据库中添加一个对象。我通过输入流从数据库中获取数据,但我无法添加数据。

也许我在Android活动或PHP代码中犯了错误。当我按下addbutton时,android activty关闭并显示主活动,并且我的数据库中没有新的obect。

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

我执行" 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 个答案:

答案 0 :(得分:2)

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