How to make JsonArray clear in android? - android

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)
}

Related

update specific item at Android GridAdapter

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();

Android getting the spinner id and name placed in the spinner

thank u for your time.
I was wondering if it is possible to get the id and name from a sql and place them both in the spinner.
with out creating a new AsyncTask and doInBackGround ect..
Witch will be active then onItemselected.
I have to little experience to make this decission.
With the JSON i have now working it only allows the ID or the NAME.
So i need to know if it is better to modify this JSON or create a new JSON with new php actions.
If i can get the confirmation to do this in the first this will save me time.
I am already 5 days at this problem.
Regards.
Nevermind i got it
private void loadSpinner(){
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + categoriesList.get(i).getId());
}
}

Iterating through JSONObjects

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
}

How to decode an array of array elements in Android

A PHP script is sending to an Android app some data in the following format
[{"event_id":"4","message":"test"},["person1","person2"]]
I want to exact the 2 elements from this array into other arrays so I can easily manipulate the data. I got to the point in which the above response from the server is being converted into as string. What I can't seem to be able to do is to parse the data into arrays. I'm trying something on the following lines:
receivedData = new JSONArray(result); //result is the string response from the server
JSONArray array1= receivedData.getJSONArray(0);
JSONArray array2= receivedData.getJSONArray(1);
int len = array1.length();
but lenis not giving me back anything :(
What am I doing wrong and how could I change it.
Many thanks
What if you start by invoking new JSONObject(result); and then pulling an array out of that? I suspect you're trying to pull an array out of something that is not an array. Your PHP should not return something wrapped in [ ] it should return it wrapped in { }... also I believe your third JSON element (the array itself) is just hanging about without a label, which I believe is illegal.
so...
if your php produced this:
{"event_id":"4","message":"test"},"people": ["person1","person2"]}
and your java was this:
JSONObject j = new JSONObject(result);
String [] people = j.getJSONArray("people");
I believe you'd have what you are after.

Getting specific value from JSONArray

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);

Categories

Resources