2016-04-19 117 views
0

我想做一個顯示用戶訂單的ListView。在下面的代碼中,我得到了「成功」的作品,但我無法獲得訂單數組。使用JSON解析Volley的Android ListView

public void getOrderList() { 
    SharedPreferences sharedPreferences = getSharedPreferences("UserData", Context.MODE_PRIVATE); 
    final String hpno = sharedPreferences.getString("hpno", DEFAULT); 
    final OrderAdapter orderAdapter = new OrderAdapter(this, R.layout.row_layout); 
    orderIdListView.setAdapter(orderAdapter); 

    Response.Listener<String> responseListener = new Response.Listener<String>() { 

     @Override 
     public void onResponse(String response) { 
      try { 
       JSONObject jsonResponse = new JSONObject(response); 
       boolean success = jsonResponse.getBoolean("success"); 

       if (success) { 
        JSONArray orderList = new JSONArray(response); 
        for (int i = 0; i < orderList.length(); i++) { 
         HashMap<String, String> map = new HashMap<String, String>(); 
         JSONObject object = orderList.getJSONObject(i); 
         map.put("order_id", "Order Number: " + object.getString("order_id")); 
         orderAdapter.add(map); 
        } 
       } else { 
        AlertDialog.Builder builder = new AlertDialog.Builder(ViewOrderActivity.this); 
        builder.setMessage("Order(s) Failed to be retrieved") 
          .setNegativeButton("Retry", null) 
          .create() 
          .show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 

    ViewOrderRequest viewOrderRequest = new ViewOrderRequest(hpno, responseListener); 
    RequestQueue queue = Volley.newRequestQueue(ViewOrderActivity.this); 
    queue.add(viewOrderRequest); 
} 

OrderAdapter:

public class OrderAdapter extends ArrayAdapter { 
    List list = new ArrayList(); 
    public OrderAdapter(Context context, int resource) { 
     super(context, resource); 
    } 

    public void add(Order order) { 
     list.add(order); 
    } 

    @Override 
    public int getCount() { 
     return list.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return list.add(position); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View row; 
     row = convertView; 
     OrderHolder orderHolder; 
     if (row == null) { 
      LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = layoutInflater.inflate(R.layout.row_layout, parent, false); 
      orderHolder = new OrderHolder(); 
      orderHolder.orderIdText = (TextView) row.findViewById(R.id.orderIdText); 
      row.setTag(orderHolder); 
     } else { 
      orderHolder = (OrderHolder) row.getTag(); 
     } 
     Order order = (Order) this.getItem(position); 
     orderHolder.orderIdText.setText(order.getOrder_id()); 
     return row; 
    } 

    static class OrderHolder { 
     TextView orderIdText; 
    } 
} 

我的PHP代碼:

<?php 
    require "init.php"; 

    $hpno = $_POST['hpno']; 

    $statement = mysqli_prepare($con, "SELECT * FROM `Order` WHERE hpno = ?") or die(mysqli_error($con)); 
    mysqli_stmt_bind_param($statement, "s", $hpno); 
    mysqli_stmt_execute($statement); 

    mysqli_stmt_store_result($statement); 
    mysqli_stmt_bind_result($statement, $order_id, $total_price, $quantity, $payment_status, $hpno, $menu_id, $ordered_on); 

    $response = array(); 
    $response["success"] = false; 

    while(mysqli_stmt_fetch($statement)){ 
     $response["success"] = true; 
     array_push($response, array("order_id"=>$order_id, "total_price"=>$total_price, "quantity"=>$quantity)); 
    } 

    echo json_encode($response); 
?> 

JSON回報:

{ 
    "success": true, 
    "0": { 
     "order_id": 21, 
     "total_price": 6, 
     "quantity": 1 
    }, 
    "1": { 
     "order_id": 22, 
     "total_price": 18, 
     "quantity": 3 
    }, 
    "2": { 
     "order_id": 23, 
     "total_price": 25, 
     "quantity": 5 
    }, 
    "3": { 
     "order_id": 24, 
     "total_price": 35, 
     "quantity": 5 
    } 
} 

的logcat:

04-19 22:43:17.280 15452-15452/wqyap762.rprqs W/System.err: org.json.JSONException: Value {"success":true,"0":{"order_id":21,"total_price":6,"quantity":1},"1":{"order_id":22,"total_price":18,"quantity":3},"2":{"order_id":23,"total_price":25,"quantity":5},"3":{"order_id":24,"total_price":35,"quantity":5}} of type org.json.JSONObject cannot be converted to JSONArray 

的錯誤是從該行:

JSONArray orderList = new JSONArray(response); 

我一直在使用從數據庫中檢索很多方法,但都沒有奏效。

+0

你能後的JSON你的web服務的回報?如果需要刪除敏感內容。 – Benoit

+0

請發佈您的適配器代碼 –

+0

@Benoit我的JSON返回null。 '$ response [「OrderList」] [] = $ row;'顯示數據庫表中的總行數,但全爲空。 –

回答

0

您的JSON格式不正確。如果你想爲intented你的代碼工作的JSON應該是:

{ 
    "success": true, 
    "values": [ { 
     "order_id": 21, 
     "total_price": 6, 
     "quantity": 1 
    }, 
    { 
     "order_id": 22, 
     "total_price": 18, 
     "quantity": 3 
    }, 
    { 
     "order_id": 23, 
     "total_price": 25, 
     "quantity": 5 
    }, 
    { 
     "order_id": 24, 
     "total_price": 35, 
     "quantity": 5 
    }] 
} 

而且你的代碼是這樣的:

JSONArray orderList = new JSONArray(response.getJSONArray("values"));

+0

我一直在嘗試,但我沒有得到這種格式。 –

+0

那麼你的問題是關於PHP中的JSON格式,而不是Android。你所遇到的問題是你試圖將你的響應解析爲一個'JSONArray',但它是一個包含密鑰的'JSONObject'。所以它不是那樣工作的。你可以枚舉鍵,但這將是一個非常醜陋的方式... – Benoit

+0

我得到了你提到的格式。但結果仍然不顯示在ListView中。 –

0

對於你需要通知你的適配器的變化開始

if (success) { 
     JSONArray orderList = new JSONArray(response); 
     for (int i = 0; i < orderList.length(); i++) { 
      HashMap<String, String> map = new HashMap<String, String>(); 
      JSONObject object = orderList.getJSONObject(i); 
      map.put("order_id", "Order Number: " + object.getString("order_id")); 
      orderAdapter.add(map); 
     } 
     oderAdapter.notifyDataSetChanged(); 
    } 

其次,這個錯誤很容易理解,你試圖將JSON解析爲類型爲JSONObject的JSONArray。

正如@Benoit說,你應該改變你的反應,當你從數據庫讀取數據,並獲得值數組,他還寫了

這裏是它解釋瞭如何分析你的數據庫結果的問題作爲JSON陣列

How to build a JSON array from mysql database

相關問題