简体   繁体   中英

Send array from android and receive at PhP server using Volley

Hi I want to send an array of String value to PhP server and PhP decode and store them in PhP variable

Here is my code at android studio

private void getEventDetailRespond(RequestQueue requestQueue) {
        JSONObject params = new JSONObject();
        try {
            for (int i=0; i <eventIDBeacon.size();i++){
                params.put(Config.EVENT_ID, eventIDBeacon.get(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Creating a JSONObject request
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,Config.DATA_URL,params.toString(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject respond) {
                            try {
                                Toast.makeText(Beacon_MainActivity.this,"eventDetail respond "+respond.toString(),Toast.LENGTH_LONG).show();
                                eventArray = new JSONArray();
                                eventDetail = new ArrayList<>();
                                eventArray = respond.getJSONArray("result");
                                eventDetail = getEventDetail(eventArray);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                            Toast.makeText(Beacon_MainActivity.this, "Unable to fetch data event Detail: " +error.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    }
                );

        //Adding request to the queue
        requestQueue.add(jsonObjectRequest);

    }

    private ArrayList getEventDetail(JSONArray j) {
        ArrayList event = new ArrayList();
        //Traversing through all the items in the json array
        for (int i = 0; i < j.length(); i++) {
            try {
                //Getting json object
                JSONObject json = j.getJSONObject(i);

                //Adding the name of the event to array list
                event.add(json.getString(Config.EVENT_TITLE));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (event.isEmpty()) eventView.setVisibility(View.INVISIBLE);
        else {
            if (beacons.size()!=0) {
                checkIn.setVisibility(View.VISIBLE);
                eventView.setVisibility(View.VISIBLE);

                spinner.setAdapter(new ArrayAdapter<String>(Beacon_MainActivity.this, android.R.layout.simple_spinner_dropdown_item, event));
            }else {
                checkIn.setVisibility(View.INVISIBLE);
                eventView.setVisibility(View.INVISIBLE);
            }

        }
        return event;
    }

And to recieve from PhP size, this is my code

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

// decoding the json array
$post = json_decode(file_get_contents("php://input"), true);


$eventID = $post['EventID'];



require_once('dbconnect.php');

$sql = "SELECT EventID, EventTitle, EventDesc, EventTime FROM Event WHERE EVENTID = '$eventID'";

$res = mysqli_query($con,$sql);

$result = array();


 while ($row = mysqli_fetch_array($res)){
        array_push($result,array(
            'EventID'=>$row['EventID'],
            'EventTitle'=>$row['EventTitle'],
            'EventDesc'=>$row['EventDesc'],
            'EventTime'=>$row['EventTime']
        ));
    }

        header('Content-Type: application/json');
    echo json_encode(array('result'=>$result), 256);

    mysqli_close($con);


}

It seem not to work as I can not send and array to PhP server and decode it on PhP server. any help is much appreciate.

First in your Object in ArrayList: create JSONObjectmethod name as getJSONObject, like this

public class EstimateObject {
String id, name, qty, price, total;
public EstimateObject(String id, String name, String qty, String price, String total, int position)
{
    this.id = id;
    this.name = name;
    this.qty = qty;
    this.price = price;
    this.total =total;
    this.position = position;
}
 public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("Id", id);
        obj.put("Name", name);
        obj.put("Qty",qty);
        obj.put("Price", price);
        obj.put("Total", total);
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

Aftrer Here is how I converted it,in my activity

    JSONObject JSONestimate = new JSONObject();
    JSONArray myarray = new JSONArray();

    for (int i = 0; i < items.size(); i++) {

        try {
            JSONestimate.put("data:" + String.valueOf(i + 1), items.get(i).getJSONObject());
            myarray.put(items.get(i).getJSONObject());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Log.d("JSONobject: ", JSONestimate.toString());
    Log.d("JSONArray : ", myarray.toString());

Here i converted both type JSONObject and JSONArray.

After in

map.put("jsonarray",myarray.toString());

And in php

$json = $_POST['jsonarray'];
$json_array = json_decode($json,true);

you have to override volley's getParams method inside your getEventDetailRespond method

 @Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
 JSONObject params = new JSONObject();
    try {
        for (int i=0; i <eventIDBeacon.size();i++){
            params.put(Config.EVENT_ID, eventIDBeacon.get(i));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
return params;
};

that's the way to send params using Volley library.. in your case you have to create this:

 Map<String, ArrayList<>> params = new          
       HashMap<String,ArrayList<>>();

where array list is your desired list

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