0

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.

5
  • Can you post the JSON your webservice returns? Remove sensitive content if needed. Commented Apr 19, 2016 at 11:45
  • Please post your Adapter code also Commented Apr 19, 2016 at 12:20
  • @Benoit My JSON returns null. $response["OrderList"][] = $row; does show the total row in the database table, but all null. Commented Apr 19, 2016 at 12:53
  • Please post the exact JSON you are receiving so that we can see where's your issue. Commented Apr 19, 2016 at 13:03
  • @Benoit Sorry to keep you waiting. I just posted it. Commented Apr 19, 2016 at 14:48

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Well then your question is about JSON formatting in PHP, not Android. The issue you have is that you are trying to parse your response as a JSONArray but it's a JSONObject containing keys. So it's not working like that. You could enumerate keys but that would be a very ugly way to do so...
I got the format that you mention. But the result still don't display in the ListView.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.