排球对象请求返回0

时间:2015-11-15 15:58:25

标签: android arrays json android-studio android-volley

我有一个包含6行的远程数据库 这是我的代码,我把它放在List中,以便我可以得到大小,
但它总是返回0.

public List<Comments> getComments() {
        final List<Comments> commentsData = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                showUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray("poi");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        Comments current = new Comments();
                        current.image = "drawable://" + R.drawable.juandirection_placeholder;
                        current.title = jsonObject.getString("title");
                        current.comment = jsonObject.getString("comment");
                        current.date = jsonObject.getString("date");
                        current.rating = Integer.parseInt(jsonObject.getString("rating"));
                        commentsData.add(current);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
        return commentsData;
    }

我需要大小才能使用。
为什么总是归零? 我甚至尝试在循环中添加一个计数器++ 但是,当我得到计数​​器的价值时,它仍为零。

1 个答案:

答案 0 :(得分:0)

JsonObjectRequest在后台线程上运行。这就是你得到列表大小为0的原因。你必须使用.blurry函数。

Exmp。

public void onResponse(JSONObject response) {}