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?
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.
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);
Related
I have an project where devices with Tasmota firmware are sending out MQTT JSON formated messages, that are used in my project to build JSONArray using .put method. Later the JSONArray changes are propagated to GridView adapter calling notifyDataSetChanged().
The challenge is to keep JSONArray structure same but with upto date (new MQTT messages arrives) data which arrive in different order then the initial JSONArray structure was. The result is that JSONArray embedded JSONObjects order changes on the fly and the gridView order changes too, that is confusing users. Temporally I tried to solve that by deleting latest JSON message from device that is sending the update from JSONArray by calling .remove and the re-adding updated Json Object calling .put method + calling notifyDataSetChanged() to reflect changes in the GridView.
//on new message arrived
sonoff_obj = mqtt.message;
for(json_position_index = 0; json_position_index < _arr_mqtt.length(); json_position_index++) {
if (_arr_mqtt.getJSONObject( json_position_index ).getString( "Topic" ).equals( _received_topic )){
_arr_mqtt.remove( json_position_index );
_arr_mqtt.put( sonoff_obj );
break;
}
}
Problem is now, that because using .put, then the new JsonObject is always added to last position in the JSONArray, also GridView layout gets reorganised, which confuses end users.
I am looking for solution how to update JsonObject in the JSONArray maintaining same index(position in the Array) or how to directly say the adapter to replace Item at specific position.
So far i can get adapter item content using .getItem( int index ); but can I tell the adapter something like in (my pseudo code) .setItem( int index , JsonObject obj) ?
For those who are facing the same challenge, ArrayList is much better choice than JsonArray, because it supports .set method which is with .notifyItemChanged() method powerful approach to modify specific position in the ArrayList. If you need for some reason to keep JSONArray format (for GridAdapter ie.), you can always export ArrayList into JSONArray like this (and of course call notifyDataSetChanged()):
my_mqtt_array = new JSONArray( my_arrayList.toString());
my_mqtt_array.notifyDataSetChanged();
I am building and android application and using pull down referees. I wanna to clear the old jsonArray data and reload the new data that coming from server.
I have tried many thinking like - JsonArray test = new JsonArray(), JsonArray test("[]");
but nothing is working can some one help me in solving this.
Try this for clearing JSONArray:
jsonArray = new JSONArray(new ArrayList<String>());
You need to run a while loop across the length of the test and at each time delete the first index. the loop will reach a stage when the length of the test is zero to show the test is not empty and and cleared.
while (test.length() > 0) {
test.remove(0)
}
I have tried several of the examples listed and none of them seem to work for some reason so I am posting a new question.
I have a JSON string coming to me however it is all objects (it is not formatted in an array). I need to parse out the Team names from this. I know I need to iterate over them as they are the keys and then store the objects in a new array.
Here is the JSON (a sample of it)
{"query":{"printrequests":[{"label":"","typeid":"_wpg","mode":2,"format":false}],"results":{"Team:Kubbchucks":{"printouts":[],"fulltext":"Team:Kubbchucks","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks","namespace":822,"exists":true},"Team:Kubbchucks
IDP":{"printouts":[],"fulltext":"Team:Kubbchucks
IDP","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks_IDP","namespace":822,"exists":true}},"serializer":"SMW\Serializers\QueryResultSerializer","version":0.5,"meta":{"hash":"8407a177d701d746edc3066a012c17d2","count":2,"offset":0}}}
What I have so far to dig down to that level of the JSON (data is the string above)
JSONObject parsing = new JSONObject(data);
JSONObject query = parsing.getJSONObject("query");
JSONObject results = query.getJSONObject("results");
This allows me to manually check for a team using :
JSONObject teamone = results.getJSONObject("Team:Kubbchucks");
This is of course not ideal. The full JSON file has almost 3000 entries and I do not know what those entries all are. I need to iterate over the results object to get the keys that start with "Team:"
I've tried a few different iterator samples but none seem to be working for me and it is starting to really frustrate me. Believe me, I've tried many things before asking the question. Any help is appreciated.
I had a similar problem some time ago.
You can do like this:
JSONObject results = query.getJSONObject("results");
Iterator<String> iterator = results.keys();
while (iterator.hasNext()) {
JSONObject team = results.getJSONObject(iterator.next());
// do stuff
}
Here's my JSON data sample:
{
"node_1.1":{
"someCrap":{
"someCrap":"SomeValue"
}
},
"node_1.2":{
"Node_1.2.1":{
"Node_1.2.1.1":{
"param1":value,
"param2":value,
"param3":"value",
"paramThatIneed":{
"ThisIsWhatIActuallyNeed":"url",
"width":96,
"height":72
}
},
"Node_1.2.1.2":{
Same as above, just that paramThatINeed might be missing, gotta place imagePlaceHolder Here
},
//and so on... there are a total of 50 of these..
}
}
}
Now I could get the node_1.1 and Node 1.2 and the sub-node of it node_1.2.1
However, there are 50 sub-nodes inside of node_1.2.1, and they will have random names returned from the server. Its in string format but they're actually ints. Its a page ID.
Now I wanna iterate through the node_1.2.1 and get those sub-nodes and access their sub-nodes and take in the URL of the paramThatINeed. If the paramThatINeed is not present, I need to put some null/dummy value.
This is the code that I tried to work it as far as I've reached:
JSONObject jsonObj = new JSONObject(jsonStr); //jsonStr is the entire JSON string
JsonObject node_1.2= jsonObj.getJsonObject("node_1.1");
JsonObject node_1.2.1 = node_1.2.getJsonObject("node_1.2.1");
What do I do after this? Because I can only getJsonObject by passing a string param to it, I tried using the for loop but it doesn't take any int param.
Also, as I said before, the nodes after that have random names and not fixed. So I'm totally confused.
Please help me out if you know how to solve this problem. Please remember there's no JsonArray in this. I'm probably thinking of editing the JSON string itself and replacing some parts of the '{' with '[' and converting it to an array :( ... I think that's a sad approach.
Use this to iterate over an object.
Android (JSONObject) How can I loop through a flat JSON object to get each key and each value
but be careful, from json object you won't get the result in original order, like in json array. The result will be in alphabetical order (I hope I was clear). And you can use optJsonobject(), instead of getJsonObject(). It will returns null, instead of throw exception. You can use opt every where instead of get.
I'm using JSON in my app and I have a button "RSS", after clicking on which I want to see the RSS feed. While logging in, I also use JSON, but everything is done in background and the next view does not depend on JSON object. In LogCat I can see something like this {"response":{"#attributes":{"count":"4","all_results_count":"4","page":"1"},"news":[{"content_id":"43366","date_added":"04-01-2010","content_title":"New News","content_data":"mika"},{"content_id":"111443","date_added":"04-11-2008","content_title"..... But how can I actually display this on Android's screen?
Use JSONTokener to parse the JSON string.
string json = getYourFeed() // some method to retrieve the json response.
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
int count = JSONObject response = object.getJSONObject("response").getJSONObject("#attributes").getInt("count");
JSONArray array = object.getJSONObject("response").getJSONArray("news");
for (int i=0; i<count; i++) {
JSONObject newsItem = array.getJSONObject(i);
Log.d("RSSReader", newsItem.getString("content_title");
}
use the get... methods of JSONObject to retrieve the rest the same way.
Update, based on your comment: I would start it simple, and then add more complexity as you get a feel for these controls. Create a String[] array with your news titles and add it to the list using an ArrayList adapter. It's very easy to use. Add an OnItemClickListener that shows a Toast with the full content.
Then, you can move to a SimpleAdapter version with a multiple columns ListView and perhaps a TabActivity that shows the full news.
http://ykyuen.wordpress.com/2010/01/03/android-simple-listview-using-simpleadapter/
http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
What code are you using to get those outputs?
I would parse it with something like a 'SAXParser' and Display it using an 'ListView'...