5

noob Android/JSON person here. I hope someone might help me?

I've looked and looked but don't think it's what I'm after. I've been working on this project all day so maybe my brain has just gone to mush... If this has been awnsered else where please point me that way :)

Anyway, I wish to get a specific object from within an JSONArray - here's what's happening so far:

  JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_obj = jArray.getJSONObject(i);

                        name = json_obj.getString("txt_title");

                }

                txt_title.setText(name);

As far as I understand result returns the entire JSONArray, then I go through the length of those results using the for loop and get the json objects. At the moment I'm only asking for values from "txt_title" in the Array. So far, so good?

Then what I want to do is, say only set the third "txt_title" value from the Array.

At the moment I would expect txt_title.setText(name) to be displaying ALL the titles in "txt_title" however it's only displaying the LAST title in the Array. This probably has something to do with the for loop?

How would I go about choosing which object is displayed?

Community
  • 1
  • 1
Willis
  • 73
  • 1
  • 1
  • 6

2 Answers2

9

You are only displaying the last one in the list right now because you are setting name each time in the loop.

name = json_obj.getString("txt_title");

this overwrites the previous value every time you iterate. If you want to have all the values, you would have to do it in an additive way.

name += json_obj.getString("txt_title");

If you want to get a specific item from the array you just need to access it using the index you want instead of a loop.

    if(jArray.length() > 2) {
         JSONObject json_obj = jArray.getJSONObject(2);   //get the 3rd item
         name = json_obj.getString("txt_title");
    }

Hope that helps you understand how to access it.

Brian ONeil
  • 4,229
  • 2
  • 23
  • 25
2

If you can ensure that the element will exist at the index you can skip the loop entirely.

JSONArray jArray = new JSONArray(result);
String name = jArray.getJSONObject(2).getString("txt_title");
txt_title.setText(name);
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • Thanks. That sounds like it could work, I shall give it a try! It's for a prototype so at the moment it's only dummy data, although in a 'real world' scenario you might have database entries being updated/deleted - what would be the best approach for something like this? – Willis Apr 01 '12 at 01:23