0

This is my code for JsonArrayRequest I think either it is incomplete or incorrect. The problem is nothing getting added into the database and I am not getting any errors. I am new to programming so I have no idea as to where I might be going wrong.

private void insertToDb() {
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, INVEST_URL,
            itemSelectedJson, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            Toast.makeText(AddInvEst.this, "The echoed response is "+response, Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> headers = new HashMap<String, String>();
            headers.put("Content-Type","application/json");
            headers.put("Accept", "application/json");
            return headers;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

This is code for creating a jsonArray

private void selectedItems() {

    billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
            .getText().toString();

    itemselected.put("custInfo", custSelected.toString());
    itemselected.put("invoiceNo", textViewInvNo.getText().toString());
    itemselected.put("barcode", barCode.getText().toString());
    itemselected.put("desc", itemDesc.getText().toString());
    itemselected.put("weight", weightLine.getText().toString());
    itemselected.put("rate", rateAmount.getText().toString());
    itemselected.put("makingAmt", makingAmount.getText().toString());
    itemselected.put("net_rate", netRate.getText().toString());
    itemselected.put("itemTotal", itemtotal.getText().toString());
    itemselected.put("vat", textViewVat.getText().toString());
    itemselected.put("sum_total", textViewSum.getText().toString());
    itemselected.put("bill_type", billType);
    itemselected.put("date", textViewCurrentDate.getText().toString());

    //Add the map to the Array
    itemSelectedJson.put(itemselected);
    index++;
}

And this is my php code.

<?php
require "init.php";
$json = file_get_contents('php://input'); 
//$data = json_decode($json,true);
// remove the ,true so the data is not all converted to arrays
$data = json_decode($json);
// Now process the array of objects
foreach ( $data as $inv ) {
    $custInfo = $inv->custInfo;
    $rate =     $inv->rate;
    $weight=    $inv->weight;
    $desc=      $inv->desc;
    $makingAmt= $inv->makingAmt;
    $vat=       $inv->vat;
    $itemTotal= $inv->itemTotal;
    $sum_total= $inv->sum_total;
    $barcode=   $inv->barcode;
    $net_rate=  $inv->net_rate;
    $date=      $inv->date;
    $invoiceNo= $inv->invoiceNo;
    $bill_type= $inv->bill_type;
    $sql = "INSERT INTO selected_items 
             (custInfo, invoiceNo, barcode, desc, 
              weight, rate, makingAmt,net_rate,
              itemTotal,vat,sum_total,bill_type,date) 
            VALUES
             ('$custInfo','$invoiceNo','$barcode','$desc',
              '$weight','$rate','$makingAmt','$net_rate',
              '$itemTotal','$vat','$sum_total','$bill_type','$date')";
    $res = mysql_query($sql,$con);
    if(!$res){
        $result = new stdClass();
        $result->status = false;
        $result->msg = mysql_error();
        echo json_encode($result);
        exit;
    }
}
?>
Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
  • 1
    `desc` is reserved keyword in mysql it must be in backtick!! https://dev.mysql.com/doc/refman/5.6/en/keywords.html – Saty Nov 30 '15 at 12:46
  • date .. same (its best to backtick them all).. – Svetoslav Nov 30 '15 at 12:47
  • @Saty thanks I'll change that but what do you mean by backtick though –  Nov 30 '15 at 12:47
  • @Svetlio `date` is keyword but not reserved check there is no **(R)** – Saty Nov 30 '15 at 12:49
  • 1
    @Saty you are right, but this doesn't change my advice.. BTW PHP has depricated Mysql lib so better use mysqli or pdo instead.. – Svetoslav Nov 30 '15 at 12:51
  • @anup check [backtick](http://superuser.com/questions/254076/how-do-i-type-the-tick-and-backtick-characters-on-windows) – Saty Nov 30 '15 at 12:52
  • @Saty I have added the backtick but still nothing is getting inserted –  Nov 30 '15 at 12:55
  • echo your query and run directly in phpmyadmin – Saty Nov 30 '15 at 12:56
  • @Saty I dont have any problem with my php code can you spot where I am going wrong on the android front.Thanks –  Nov 30 '15 at 13:00
  • @anup sorry dude I am not a android developer!! – Saty Nov 30 '15 at 13:01
  • When you POST something you need to tell in the header what kind of data you are POSTing. Check out the [answer here](http://stackoverflow.com/questions/24284651/volley-not-calling-getparams-for-standard-post-request). You need to add the `getHeaders( )` method too. – denvercoder9 Nov 30 '15 at 13:29
  • @RafiduzzamanSonnet where exactly am I supposed to implement this method. –  Nov 30 '15 at 13:35
  • @RafiduzzamanSonnet please check my updated code for InsertToDb –  Nov 30 '15 at 13:43
  • @anup See the answer below given by Daniel. Instead of the method getParams( ) , implement the getHeaders( ) method. [Here](https://gist.github.com/mombrea/7250835) is an example with StringRequest but it works with JsonRequest too. Appropriate headers for json requests are given [here](https://developer.atlassian.com/display/CROWDDEV/JSON+Requests+and+Responses#JSONRequestsandResponses-HTTPHeaders) – denvercoder9 Nov 30 '15 at 13:44
  • @anup you don't need getParamsEncoding( ). And change headers to appropriate values – denvercoder9 Nov 30 '15 at 13:47
  • @RafiduzzamanSonnet Ihave made the required changes please check –  Nov 30 '15 at 13:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96561/discussion-between-rafiduzzaman-sonnet-and-anup). – denvercoder9 Nov 30 '15 at 13:50
  • @RafiduzzamanSonnet please check my msg.Thanks:) –  Dec 01 '15 at 14:30

1 Answers1

0

You missed to add a method getParams() inside the post request, it should have this structure

StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    errorHandler(error);
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            //Adding parameters to request
            params.put("KEY1", key1);
            params.put("KEY2", key2);

            //returning parameter
            return params;
        }
    };

    //Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
Daniel
  • 53
  • 1
  • 7
  • I am trying to send an jsonArray and not Strings. –  Nov 30 '15 at 13:30
  • it's the same, you have only to change where there it says StringReques in JsonArray request, and put inside the listener . Look it for more information: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ – Daniel Nov 30 '15 at 13:33