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'...
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 trying to build an android app that uses the github api.
I am facing an issue with JSON parsing.
I have a function that looks for JSONArray and produces the corresponding JSON data to show them in the UI, but the problem is the function works only when the JSON root is an array.
For ex-
when the url is "https://api.github.com/users", it works perfect, since the root is an array but now when I go to url such as "https://api.github.com/users/mojombo", the JSON root becomes an object. How do I parse it now in order to show the data in the UI ??
Do I have to write separate function for JSONObjects??
**The java function is **
private void makeJSON(String res) throws JSONException {
JSONArray root = new JSONArray(res);
for (int i =0; i<root.length();i++){
JSONObject jsonObject= root.getJSONObject(i);
String name = jsonObject.getString("login");
int id = jsonObject.getInt("id");
}
}
The answer is yes. Here you try to parse different types of objects (users list and particular user info) in single function. This is violation of single responsibility principle.
You can divide this function in 2 (to parse users list and user data) but better is to use Retrofit 2 for this.
I am trying to search from JSON code that has been received beforehand..
I was wondering are there any efficient way to search specific object?
Or should i use straight forward search like looping and if statement?
I have parsing the JSON successfully, and it stored in my String variable..
The JSON contains Array of Objects..
Now i want to search for specific ObjectName and get the Whole Objects..
The JSON will be like
[
{
"name":"blank",
"date":"2014-06-05T00:44:30Z",
"boolean":null,
},
{
"name":"hello",
"date":"2013-05-04T00:43:20Z",
"boolean":null,
}
]
I want to search for name = "hello" and get the last Array returned
Can anyone show me how?
Thanks a lot!
You can use something like this:
String name;
JSONObject searchObject;
JSONArray array = new JSONArray(yourJsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject currObject = array.getJSONObject(i);
name = currObject.getString("name");
if(name == "hello")
{
searchObject = currObject
}
}
return searchObject
For big data you can't use search in every element imagin you have a 50K user you can't search in every 50k title to found your element I advise you to the backend - Web Developer - do this it will be easier to you and more faster how you can do this?
You just need a space to pass search text in JSON Url then post it and retrieve searched data from him
Try to use a web server with (PHP) and set your search element in GET like this.
Then the php search function will give you the full Json needed to your search. Also you can set pagination for this search like this.
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.
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);