BVtp
BVtp

Reputation: 2480

getting JSONArrays with Volley

I am trying to get a JSONArray from a server but getting all kinds of errors. EDIT : tried adding all these imports.

    import android.support.v7.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.Response.ErrorListener;


    public class VolleyFetcher extends AppCompatActivity
    {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://xxxxxx.json"; 

        JsonObjectRequest jsObjRequest = new JsonObjectRequest(
                Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                    // TODO Auto-generated method stub
                }
                }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) 
                {
                    // TODO Auto-generated method stub
                }
                });

        queue.add(jsObjRequest);    
    }

My errors:

Response cannot be resolved to a type

JSONArray cannot be resolved to a type

Syntax error on token "jsObjRequest", VariableDeclaratorId expected after this token (//line : queue.add(jsObjRequest)

Any advice would be very much appreciated.

Upvotes: 1

Views: 961

Answers (1)

Gil Moshayof
Gil Moshayof

Reputation: 16781

JSONObjectRequest should be used if the result returned is a JSON Object.

If you're expecting to get a JSON Array back, you should use JSONArrayRequest. This request should be included in Volley's toolbox package.

The result request declaration should look like this:

JsonArrayRequest request = new JsonArrayRequest("http://my.url.com/", new Response.Listener<JSONArray>()
        {
            @Override
            public void onResponse(JSONArray response)
            {

            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {

            }
        });

Upvotes: 2

Related Questions