简体   繁体   中英

Send data list to server using Volley

I need to pass data list to server using volley and access that data using PHP. From android application I need to pass all the data in one table and access that data on server. You can think of it as a passing data in shopping cart to the server.

I can get the data from database as a list. I need to submit data to server and access it.

RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, NetworkHandler.ORDER, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try{
            Log.d(LogMessages.ORDER_CONFIRM,response.toString());
        }
        catch(Exception ex){
            Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        List<Food> listCart = db.getAllCartItems();
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("orderitems",listCart .toString());
        return parameters;
    }
};
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES*2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);

If you mean to send variant length list of data to server, generally I will do this: 1. send a "count" parameter to indicate how many records 2. send "record_1", "record_2".... parameters to server

On server side you should check "count" first then you check "recored_#" from 1 to the count you just get.

You can use json format to send multiple data to server and use gson to convert to json array

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(listCart ).getAsJsonArray();

I found a solution . I used GSON library. This is solution.

List<Food> listCart = db.getAllCartItems();
                             Gson gson = new Gson();
                             String data = gson.toJson(listCart);
                             Log.d(LogMessages.ORDER_CONFIRM,data);
                             Map<String, String> parameters = new HashMap<String, String>();
                             parameters.put("orderitems",data);

In the PHP side i get the orderitems using $_POST['orderitems'] and decoded that data using json_decode.Then I can access each object.

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