2015-11-30 2 views
0

Это мой код для JsonArrayRequest. Я думаю, что он неполный или неправильный. Проблема в том, что в базу данных ничего не добавляется, и я не получаю никаких ошибок. Я новичок в программировании, поэтому я понятия не имею, где Возможно, я ошибаюсь.POST json array в базу данных Mysql с использованием JsonArrayRequest с использованием volley in android?

частная пустота insertToDb() { JsonArrayRequest jsonArrayRequest = новый JsonArrayRequest (Request.Method.POST, INVEST_URL, itemSelectedJson, новый Response.Listener() { @Override общественного недействительными onResponse (JSONArray ответ) {

  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); 
} 

Это код для создания 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++; 
} 

И это мой php-код.

<?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; 
    } 
} 
?> 
+1

'desc' зарезервирован ключевое слово в MySQL он должен быть в кавычкой !! https://dev.mysql.com/doc/refman/5.6/en/keywords.html – Saty

+0

дата .. то же самое (самое лучшее, чтобы вернуть их все). – Svetoslav

+0

@Saty thanks Я изменю это, но что вы имеете в виду by backtick хотя –

ответ

0

Вы пропустили добавить метод getParams() внутри запроса пост, он должен иметь такую ​​структуру

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); 
} 
+0

Я пытаюсь отправить jsonArray, а не строки. –

+0

Это то же самое, вам нужно только изменить там, где там написано StringReques в запросе JsonArray, и положить внутри слушателя . Посмотрите его для получения дополнительной информации: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ – Daniel

Смежные вопросы