有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

即使Android应用成功发布数据,java数据库也不会更新

我有一个安卓应用程序,我正在编程,将一组数据发布到本地服务器的php文件中。数据格式如下所示。 名称1->;数量1 名称2->;数量2 我试图将其作为json数组发送,但问题是,每当我发送数据时,它都表明它成功地发布了数据。然而,我看不到数据库的任何变化,这应该是由安卓应用程序发送的数据造成的。如果有人指导或解决了我的这个问题,我会非常感激。请帮帮我

下面是我用来发送和接收数据的类

这是发送数据的类

public class Thirdscreen extends Activity {

    private static String url = "http://10.0.2.2/bootstrap-dist/postingdata.php";
    public ArrayList<QantityModelProduct> quantitymodel=new ArrayList<QantityModelProduct>();




    // Progress Dialog

    private ProgressDialog pDialog;

    // Json parser object
    JSONParser jsonParser = new JSONParser();




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thirdscreen);
        QantityModelProduct qmp;



        TextView showCartContent = (TextView) findViewById(R.id.showCart);
        TextView showCarttotal = (TextView) findViewById(R.id.showtotal);
        Button btn = (Button) findViewById(R.id.subtractQuantity);

        final Controller aController = (Controller) getApplicationContext();

        int cartSize = aController.getCart().getCartSize();

        String showString = "";
        int total = 0;

        for (int i = 0; i < cartSize; i++) {

            String pName = aController.getCart().getProducts(i)
                    .getProductName();
            int pPrice = aController.getCart().getProducts(i).getProductPrice();
            int quantity = aController.getCart().getProducts(i)
                    .getProductQuantity();
            int dataProQuantityStore = aController.getCart()
                    .getProducts(i).getDatabaseProductQuantity();

            String pDisc = aController.getCart().getProducts(i)
                    .getProductDesc();

            total = total + (pPrice * quantity);
            showString += "\n\nProduct Name : " + pName + "\n" + "Price : "
                    + pPrice + "\t" + "Quantity: " + quantity + "\n"
                    + "Discription : " + pDisc + ""
                    + "\n -----------------------------------";



            //databaseQuantity-Current quantity
            int finalVal = dataProQuantityStore - quantity;
            String finalstringValue=""+finalVal;

            qmp=new QantityModelProduct(pName,finalstringValue);
            quantitymodel.add(qmp);


        }

        showCarttotal.setText("Your Total is: " + total + "Tk");

        showCartContent.setText(showString);


        final int productSize=quantitymodel.size();
        Toast.makeText(getApplicationContext(),"Array size: "+productSize, Toast.LENGTH_SHORT).show();

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {


                new getQuantity().execute();

            }
        });



    }

    class getQuantity extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            pDialog = new ProgressDialog(Thirdscreen.this);

            pDialog.setMessage("Processing your request..");

            pDialog.setIndeterminate(false);

            pDialog.setCancelable(true);

            pDialog.show();

        }

        @Override
        protected String doInBackground(String... params) {



                    JSONArray jsonArray = new JSONArray();
                    for (int i=0; i < quantitymodel.size(); i++) {
                            jsonArray.put(quantitymodel.get(i).getJSONObject());
                    }


            jsonParser.getandpostJSONFromUrl(url, "POST",jsonArray);


            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            final Controller aController = (Controller) getApplicationContext();

            // dismiss the dialog once done

            pDialog.dismiss();
            aController.getCart().clearCart();
            aController.getProductsArraylist().clear();
            Toast.makeText(getBaseContext(), "I am in second loop", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getBaseContext(), FirstScreen.class);
            finish();
            startActivity(i);

        }

    }

}



public class QantityModelProduct {
    private String ProductName;
    private String ProductQuantity;

    public QantityModelProduct(String productName, String productQuantity) {

        ProductName = productName;
        ProductQuantity = productQuantity;
    }

    public JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("Name", ProductName);
            obj.put("Quantity", ProductQuantity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

}

下面是Json解析器类

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {

        // Making HTTP request
        try {
            // defaultHttpClient
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new StringEntity(name.toString()));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                httpPost.setHeader("jsonArray",json.toString());
                HttpEntity httpEntity = httpResponse.getEntity();
                int response = httpResponse.getStatusLine().getStatusCode();
                is = httpEntity.getContent();
                Log.e("posting Status", "Post status: " + response);
            }
            if (method == "GET") {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (method == "POST") {
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
            } catch (Exception e) {
                Log.e("Buffer error", "Buffer error" + e);
            }

        } else if (method == "GET") {

            try {

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();

            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
        }

        // return JSON String
        return jObj;

    }

}

最后是接收这些数据的php文件

?php
    define('DB_NAME', 'sshop');
                    define('DB_USER', 'root');
                    define('DB_PASSWORD', '');
                    define('DB_HOST', 'localhost');


                    $link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);

                    if(!$link){
                    die('could not connect: '.msql_error());
                    }

                    $db_selected=mysql_select_db(DB_NAME, $link);

                    if(!$db_selected){
                    die('Can not  use '.DB_NAME.':'.mysql_error());
                    }


     if (isset($_POST['jsonArray'])){ 
                        $jArray = json_decode($jsonArray,true);

                foreach ($jArray['jsonArray'] as $obj) {
                             $ProductName = $obj['Name'];   //String
                             $ProductQuantity= $obj['Quantity'];
                             $sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
                             echo   $ProductName." ".$ProductQuantity;
                         }


                     }else {
                        echo 'empty';
                    }
    ?>

共 (1) 个答案

  1. # 1 楼答案

    首先,不应该使用==

    试试这个

            if (method.equals("POST"))
    

    接下来,要进行调试,请通过发送与响应相同的请求,查看通过Android应用程序向PHP Web服务发送的数据。因此,您确切地知道是否正在发送数据

    如果上述步骤工作正常,则表示问题出在PHP端。使用Chrome中的http://hurl.it或Postman客户端通过浏览器发送帖子,然后调试PHP代码。查看是否正在插入数据

    这应该能解决你的问题

    尼廷