King of Masses
King of Masses

Reputation: 18775

Getting empty array [] response with volley Json

I am getting some data from the API with a web server call. If i use the basic web call (with HttpGet) i am able to get the data what i am expecting. But by using Volley Json i am getting an empty array [] as a response.

I get the following jsonarray response.

[
  {
  "nickname":"panikos",
  "username":"[email protected]",
  "user_type":"LEADER",
  "latest_steps":"2"
  },
{
  "nickname":"nikki",
  "username":"[email protected]",
  "user_type":"MASTER",
  "latest_steps":"3"
  },
...........
...........
...........
...........
]

Here is my code to get the data from server by using volley

JsonArrayRequest arrReq = new JsonArrayRequest(lUrl, new 
        Response.Listener<JSONArray>() 
        {
    public void onResponse(JSONArray arg0)
    {
        Log.d("debug","json Array"+arg0.toString());

        mListener.notifyResponse(arg0.toString());
    };
        }, new Response.ErrorListener() 
        {
            @Override
            public void onErrorResponse(VolleyError arg0) {

                Log.d("debug", "Error Response"+arg0.toString()); 

                if (arg0.networkResponse == null) {
                    if (arg0.getClass().equals(TimeoutError.class)) {
                        // Show timeout error message   
                        mListener.notifyConnection("Oops.Timeout! Please check your connection.");
                    }
                }else{
                    mListener.notifyError(arg0);    

                }
            }

        })
{
    public Map<String, String> getHeaders() throws AuthFailureError {

        HashMap<String, String> params = new HashMap<String, String>();
        String creds = String.format("%s:%s",XippXX,XXcvXX);
        String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
        params.put("Authorization", auth);
        return params;
    }
};

AppController.getInstance().adToRequestQure(arrReq);

By using this code every time i am getting an empty array [] in the volley Json response. But i tried the same with basic Http call (by using Asynctask) it is giving the proper data what i am expecting.

This is my Basic code for getting the data with normal web request call::

@Override
protected Void doInBackground(String... params) {

    try {

        HttpGet request=new HttpGet(params[0]);
        DefaultHttpClient httpClient=new DefaultHttpClient();

        String creds = String.format("%s:%s","XippXX","XXcvXX");
        String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);

        request.setHeader("Authorization", auth);
        HttpResponse response=httpClient.execute(request);  
        HttpEntity Entity=response.getEntity();
        String jsondata = EntityUtils.toString(Entity);

        Log.d("debug", "Json Data in Asynctask:: "+jsondata);

        JSONArray lJsonArray=new JSONArray(jsondata);

        Log.d("debug", "Json Array Data:: "+lJsonArray.toString());


    }       
    catch (Exception e) {

        e.printStackTrace();            
    }

    return null;
}  

This code is working perfectly.. but i am glad to know where i am making the mistake in the Volley Json ? I tried too many scenario's (those i can't shown here) like StringRequest, and some other things like Base64.DEFAULT but no luck.

Sorry for the poor english and long question. Any one can point out me.. Thank you !!!

Upvotes: 2

Views: 2075

Answers (1)

TommySM
TommySM

Reputation: 3883

I had a similar problem, the root of the issue is that you're trying to perform a GET with params, it's different than a POST, so you need to modify your request.

This is a general template that might help you, try the request like this (with your modifications to the param..):

EDITED:

       Map<String, Object> params = new HashMap<>() ;
       String creds = String.format("%s:%s",XippXX,XXcvXX);
       String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
       params.put("Authorization", auth);
       String urlWithParams = createGetWithParams(originalUrl, params);

        DecodedStringRequest request = new DecodedStringRequest(Request.Method.GET, urlWithParams, 
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        Log.d(TAG + ": ", "Volley Response: " + response.toString());

                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        if (null != error.networkResponse)
                        {
                            Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
                        }
                    }
                });

        requestQueue.add(request);

and here check for your response here:

public class DecodedStringRequest extends StringRequest
{
    private static final String TAG = "DecodedStringRequest";
    private final Response.Listener<String> mListener;

    public DecodedStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener)
    {
        super(method,url, listener, errorListener);
        mListener = listener;
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response)
    {
        try
        {
            //add some more of your magic here if needed... maybe print the data to see
            String responseBody = new String(response.data, "utf-8");
            return (Response.success(responseBody, getCacheEntry()));
        }
        catch (UnsupportedEncodingException e)
        {
            VolleyLog.e("UnsupportedEncodingException");
            Log.d(TAG +" NetworkResponse Exception", e.getMessage() );
            return (Response.success("Uploaded, problem with url return", getCacheEntry()));
        }
    }

    @Override
    protected void deliverResponse(String response)
    {
        mListener.onResponse(response);
    }
}

oh and:

private String createGetWithParams(String url, Map<String, Object> params)
{
    StringBuilder builder = new StringBuilder();
    for (String key : params.keySet())
    {
        Object value = params.get(key);
        if (value != null)
        {
            try
            {
                value = URLEncoder.encode(String.valueOf(value), HTTP.UTF_8);
                if (builder.length() > 0)
                    builder.append("&");
                builder.append(key).append("=").append(value);
            }
            catch (UnsupportedEncodingException e)
            {
                Log.d(TAG + " createGetWithParams: ", e.getMessage());
            }
        }
    }
    return (url + "?" + builder.toString());
}

Hope this helps!

Upvotes: 2

Related Questions