【问题标题】:Android Volley how to post array of custom objectAndroid Volley如何发布自定义对象数组
【发布时间】:2017-07-19 11:41:13
【问题描述】:

我是 volley 的新手,我需要将一组自定义对象发布到 PHP api 以便将其保存在 MYSQL 数据库中,我该如何完成?

注意:我知道我下面的代码只会传递我数组的最后一个对象

这是我的对象:

public class object {

String name;
Integer qty;
Integer price;
}

和我的代码:

final ArrayList<object> myarray = new ArrayList<>();
        myarray.add(ob1);
        myarray.add(ob2);
        RequestQueue queue = Volley.newRequestQueue(this);
        JSONObject jsonArray = new JSONObject();
        try {
            int i = 0;
            for (object obj : myarray) {

                jsonArray.put("id",i++);
                jsonArray.put("name",obj.name);
                jsonArray.put("qty",obj.qty);
                jsonArray.put("price",obj.price);
            }
            Log.i("JSON ARRAY ", jsonArray.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, API_URL, jsonArray, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i("RESPONSE",response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> params = new HashMap<>();
                return params;
            }
        }; queue.add(request);
    }

【问题讨论】:

  • 检查您的后端/php 响应。我怀疑这是错误的
  • 在你的服务器端检查并响应
  • @SathishKumarJ 我的第一个问题是我的代码只发布了一个对象而不是整个数组这是我的问题

标签: php android android-volley


【解决方案1】:

需要为每个循环添加你的JSONObjectJSONArray

JSONArray jsonArray = new JSONArray();

int i = 0;
  for (object obj : myarray) {
     JSONObject jsonObj= new JSONObject();
     jsonObj.put("id", i++);
     jsonObj.put("name", nameStr);
     jsonObj.put("qty", qtyStr);
     jsonObj.put("price", priceStr);

     jsonArray.put(jsonObj);

}

Log.i("JSON ARRAY ", jsonArray.toString());

这可能对你有帮助。

【讨论】:

  • 更改代码后 JsonArray 为 ["{\"id\":0,\"name\":\"item1\",\"qty\":2,\"price\":334}","{\"id\":1,\"name\":\"item2\",\"qty\":4,\"price\":399}"] 为什么会这样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
相关资源
最近更新 更多