dss087358 2016-03-12 12:09
浏览 25
已采纳

too long

I try to add an object in my external databse with a JSON. I arrive to get datas from the database, with an inputstream but I can't add a data.

Maybe I have make a mistake in my Android activity or in my PHP code. When I push the addbutton the android activty close and the main activity is displayed and there is no new obect in my database.

I have searched on the web but a lot of tutorial use deprecated ressources.

I execute the "doInBackground" function when pushing a button.

I just want to use java or android native code and don't want to modify my graddle script.

My database contains just a table with the name of town and the primary key.

My java code :

    /**
     * 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();
        }
        }
}

My Php code :

<?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
", $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条回答 默认 最新

  • duanjian3338 2016-03-14 08:39
    关注

    You have created jsonObject.put("username", name);in the android Async task and you have try to get the data on the PHP code by using $name = $_POST['name']. Please change this to $name = $_POST['username']. I think that is the issue please check that,Thanks

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条