简体   繁体   中英

How to retrieve JSONObject from JSONArray request using Flickr API?

I want to retrieve comments from a Flickr photo in my Android app, and have created a JSONObjectRequest using the following code:

public void loadComments(ImageInfo photo) {

        //clear the comments arraylist ready for new request
    NetworkMgr.getInstance(this).commentsList.clear();
    NetworkMgr netMgr = NetworkMgr.getInstance(getApplicationContext());
    RequestQueue requestQueue = netMgr.requestQueue;

    String id = photo.id;

    String url = "https://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&api_key=MY_API_KEY&format=json&nojsoncallback=1&extras=authorname,_content&photo_id=" + id;

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, responseListener, errorListener);

    requestQueue.add(request);

    adapter.notifyDataSetChanged();     
}

The photo ID is correctly being retrieved and appended to the String url, and below I use a response listener to get authorname and _content, from each comment object:

private Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            JSONObject comments = response.getJSONObject("comments");
            JSONArray commentList = comments.getJSONArray("comment");

            for (int i = 0; i < commentList.length(); i++) {
                ImageInfo newComment = new ImageInfo();

                JSONObject comment = commentList.getJSONObject(i);

                newComment.authorname = comment.getString("authorname");
                newComment.commentContent = comment.getString("_content");

                //add data to arraylist
                NetworkMgr.getInstance(DetailsActivity.this).commentsList.add(newComment);
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        adapter.notifyDataSetChanged();
    }
};

private Response.ErrorListener errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    }
};

However when I put this url in my browser to view the JSON data, the comment JSONObject is non-existent.

How The JSON Response Should Look <<<< How My JSON Response Looks <<<<

Does anybody know why I cannot retrieve the JSON comment object and its data?

Try this

  • Put this in your loop

      JSONObject allvaluesJsonObject=new JSONObject(); allvaluesJsonObject=jsonArray.getJSONObject(i); 
  • remove this ImageInfo newComment = new ImageInfo();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM