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();
Related
I have a raw json file like this
{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
{"_id":1270260,"name":"State of Haryāna","country":"IN","coord":{"lon":76,"lat":29}}
{"_id":708546,"name":"Holubynka","country":"UA","coord":{"lon":33.900002,"lat":44.599998}}
{"_id":1283710,"name":"Bāgmatī Zone","country":"NP","coord":{"lon":85.416664,"lat":28}}
{"_id":529334,"name":"Mar’ina Roshcha","country":"RU","coord":{"lon":37.611111,"lat":55.796391}}
{"_id":1269750,"name":"Republic of India","country":"IN","coord":{"lon":77,"lat":20}}
{"_id":1283240,"name":"Kathmandu","country":"NP","coord":{"lon":85.316666,"lat":27.716667}}
{"_id":703363,"name":"Laspi","country":"UA","coord":{"lon":33.733334,"lat":44.416668}}
It is NOT an JSON array - it is a huge list of JSON objects. Here Populate the spinner from JSON In Android, here Convert json array to list of json(raw) strings here android how to convert json array to string array or even here https://developer.android.com/guide/topics/ui/controls/spinner.html it is assumed that I have a JSON array or static data. I'd like to have two spinners in which one is for country and second one is for city. Let's assume I have list of countries so it will be a static data. I'd like the second spinner to dynamically load from raw json file all cities that corresponds to selected city in first spinner. I think that I can handle spinners thing but how can I load data from raw json file into spinner? Do I need to modify this raw file so that it will be a json array and then do something like this:
JSONArray jsonArray = new JSONArray(arraytitle);
List<String> list = new ArrayList<String());
for(int i = 0 ; i < jsonArray.length();i++){
list.add(jsonArray.getJSONObject(i));
}
EDIT
I found this answer https://stackoverflow.com/a/26780581/4671908 - if I will succeed I will post an answer
So you have two questions:
How to update the second Spinner dynamically when the first Spinner is updated
Three thing you need to do:
Implement AdapterView.OnItemSelectedListener
Update the backed data set inside the adapter of the second Spinner. In your case it would be a list of city. (To do this you need to create your own adapter extended from ArrayAdapter)
Call adapter.notifyDataSetChanged()
How to use the JSON
There are several solutions there. But it would be hard for others to provide the one that would suit your case the best without knowing any detail of the requirement.
Just remember one thing when you face design problem:
Do the simplest thing first.
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)
}
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.
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);
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'...