繁体   English   中英

使用 Volley 从 android 发送数组并在 PhP 服务器上接收

[英]Send array from android and receive at PhP server using Volley

嗨,我想将一个字符串值数组发送到 PhP 服务器和 PhP 解码并将它们存储在 PhP 变量中

这是我在 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;
    }

并从 PhP 大小接收,这是我的代码

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


}

它似乎不起作用,因为我无法将数组发送到 PhP 服务器并在 PhP 服务器上对其进行解码。 任何帮助都非常感谢。

首先在 ArrayList 中的对象中:将 JSONObjectmethod 名称创建为 getJSONObject,如下所示

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

在我的活动中,这是我如何转换它的

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

在这里,我转换了 JSONObject 和 JSONArray 类型。

进入后

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

在 php 中

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

您必须在 getEventDetailRespond 方法中覆盖 volley 的 getParams 方法

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

这就是使用 Volley 库发送参数的方式。在你的情况下,你必须创建这个:

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

其中数组列表是您想要的列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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