如果空请求JSONArray应该被识别

时间:2019-05-27 00:46:11

标签: android android-volley

我正在使用Volley从远程PHP脚本获取JSON。 有时,JSON数组为空。

这是我的代码:

    /**
     * enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call')
     * Determines how the return key should look.
     */
    returnKeyType?: ReturnKeyTypeOptions;

如果JSON数组为空,那么我会收到响应侦听器消息,说data []为空,但是Toast没有显示,并且微调器的可见性也没有达到预期。

当收到的JSON数组为空时,如何更改代码以启动Toast并将微调框的可见性设置为GONE?

2 个答案:

答案 0 :(得分:1)

  • public void onResponse(String response)意味着您请求成功获得响应并成功解析,但是此回调并不意味着数据值不为空!

  • public void onErrorResponse(VolleyError error)表示请求未能获得响应,可能是错误的http代码,或者请求成功但解析失败。

因此,您希望在请求成功但data array为空时想做一些事情,因此应在public void onResponse(String response)方法中都添加逻辑以检查successfully response但数据是空的情况

@Override
public void onResponse(String response) {
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray array = jsonObject.getJSONArray("data");


        if (array == null || array.length() == 0) {

            //data array is empty

            // add the logic you want

        } else {

            //data array not empty
            for (int i = 0; i < array.length(); i++) {
                JSONObject ob = array.getJSONObject(i);
                Notificacion listData = new Notificacion(ob.getString("id_notificacion")
                        , ob.getString("texto"),
                        ob.getString("fecha"),
                        ob.getString("nombre"),
                        ob.getString("nombre") + " " + ob.getString("apellidos"),
                        ob.getString("profesor"),
                        ob.getString("tutor"),
                        ob.getString("estado"),
                        ob.getString("envia_tutor"),
                        ob.getString("envia_profesor")


                );
                list_data.add(listData);
                spinner.setVisibility(View.GONE);
            }
            rv.setAdapter(adapter);
        }

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

答案 1 :(得分:1)

您应该在代码中进行如下更改:

StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                         if (array.length()==0){
                        Toast.makeText(getActivity(),
                    "No tienes notificaciones.", Toast.LENGTH_LONG)
                    .show();
                     spinner.setVisibility(View.GONE);
                           }else{
                        for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                  );
                        list_data.add(listData);
                        spinner.setVisibility(View.VISIBLE);
                    }
                    rv.setAdapter(adapter);
                   }



                } catch (JSONException e) {
                    e.printStackTrace();
              spinner.setVisibility(View.GONE);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);

                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);