Why is Volley returning null value for response object

馋奶兔 提交于 2019-12-13 05:18:02

问题


Here is my onResponse method

public void onResponse(SongInfo response) {

    Log.v("TAG", "Response value is "+String.valueOf(response.artworkUrl30));
    // Prints "Response value is null"
}

String.valueOf(response.artworkUrl30)) should return a URL

Here I set up my request queue singleton

Static `mRequestQueue` variable and method 

public static RequestQueue mRequestQueue;

public static RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(MainActivity.getAppContext());
    }
    return mRequestQueue;
}

Here I make the request to get the the JSON object

(Actually there are multiple JSON object at the URL)

getRequestQueue();

String JSONURL = "https://itunes.apple.com/search?term=michael+jackson";

GsonRequest<SongInfo> myReq = new GsonRequest<SongInfo>(
    Request.Method.GET,
    JSONURL,
    SongInfo.class,
    null,
    createMyReqSuccessListener(),
    createMyReqErrorListener());

mRequestQueue.add(myReq);

Here is my success response listener with onResponse method

private Response.Listener<SongInfo> createMyReqSuccessListener() {
    return new Response.Listener<SongInfo>() {
        @Override
        public void onResponse(SongInfo response) {
            // Do whatever you want to do with response;
            // Like response.tags.getListing_count(); etc. etc.

            Log.v("TAG", "This is the value of the string"+String.valueOf(response.artworkUrl30));
        }
    };
}

Here is my error listener

private Response.ErrorListener createMyReqErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // Do whatever you want to do with error.getMessage();
        }
    };
}

Here is my GsonRequest class

public class GsonRequest<T> extends Request<T> {

    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Response.Listener<T> listener; // success listener

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param clazz Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */

    public GsonRequest(int method,
                       String url,
                       Class<T> clazz,
                       Map<String, String> headers,
                       Response.Listener<T> listener, // success listener
                       Response.ErrorListener errorListener) { // error listener

        super(method, url, errorListener); // error listener
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener; // success listener
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

Here is SongInfo class

public class SongInfo {

    public String wrapperType;
    public String kind;
    public Integer artistId;
    public Integer collectionId;
    public Integer trackId;
    public String artistName;
    public String collectionName;
    public String trackName;
    public String collectionCensoredName;
    public String trackCensoredName;
    public String artistViewUrl;
    public String collectionViewUrl;
    public String trackViewUrl;
    public String previewUrl;
    public String artworkUrl30;
    public String artworkUrl60;
    public String artworkUrl100;
    public Float collectionPrice;
    public Float trackPrice;
    public String releaseDate;
    public String collectionExplicitness;
    public String trackExplicitness;
    public Integer discCount;
    public Integer discNumber;
    public Integer trackCount;
    public Integer trackNumber;
    public Integer trackTimeMillis;
    public String country;
    public String currency;
    public String primaryGenreName;
    public String radioStationUrl;
    public Boolean isStreamable;
}

回答1:


I don't think you can just map the Json response as if it's completely flat, and all fields are located at the root of the Json hierarchy.

Your SongInfo model should probably look like this:

public class SongInfo {

    public int resultCount;
    public List<Results> results;
}

And you'll need a Results object, something like:

public class Results {
    public String wrapperType;
    public String kind;
    .
    .
    .
    public String artworkUrl30;
}



回答2:


If you are expecting an JsonObject as Response use Volley JsonObjectRequest,else JsonArray as response, you have to make Volley JsonArrayRequest.

After getting the response make the Gson to handle the response data with SongInfo class.

If you are thinking to use other Library for Network call, I suggest you this, enter link description here



来源:https://stackoverflow.com/questions/33991640/why-is-volley-returning-null-value-for-response-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!