简体   繁体   中英

Android ListView using JSON Parsing with Volley

I want to do a ListView that shows the user's orders. In the code below, I got "success" works but I can't get the order array to appear.

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

My PHP code:

<?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 Return:

{
    "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

The error is from this line:

JSONArray orderList = new JSONArray(response);

I have been using many methods to retrieved from database, but all did not work.

Your JSON isn't correctly formatted. If you want your code to work as intented your JSON should be:

{
    "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
    }]
}

And your code something like:

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

For a start you need to notify your adapter's changes

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

Secondly, that error is pretty simple to understand, you are trying to parse a json as JSONArray that is of type JSONObject.

As @Benoit said, you should change your response when you fetch the data from the database, and get the values as array as he also wrote

Here is a question where it's explained how to parse your database results as json array

How to build a JSON array from mysql database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM