i know i have posted a lot of questions on the same topic but i keep coming across issues i don't really know how to solve. thank you to everyone that has helped me i rally do appreciate it. i think i now know the error some i'm going to post everything clearly for you. i am trying to parse json from a Url and populate a list so heres the json feed in this case i just want the title
{"code":200,"error":null,"data":{"news":[{"news_id":"8086","title":"Tickets for Player of the Year award on general sale","tagline":"Event to be held Sunday 25th March at Holiday Inn, Barnsley","content":"Tickets for the inaugural Evo-Stik NPL Player of the Year event are now on sale to the general public.\r\n\r\nPriced at \u00a335, tickets include a three course meal, plus entertainment from renowned tenor Martin Toal and guest speaker Fred Eyre.\r\n\r\nAwards at the event include the Player and Young Player of the Year for each division, as well as divisional teams of the year, the Fans\u2019 Player of the Year and a League Merit award.\r\n\r\nTo purchase your ticket, send a cheque for \u00a335 payable to \u201cNorthern Premier League\u201d to Alan Ogley, 21 Ibberson Avenue, Mapplewell, Barnsley, S75 6BJ. Please include a return address for the tickets to be sent to, and the names of those attending. \r\n\r\nFor more information, e-mail Tom Snee or contact Event organiser Alan Ogley on 07747 576 415\r\n\r\nNote: Clubs can still order tickets by e-mailing Angie Firth - simply state how many tickets you require and you will be invoiced accordingly.\r\n\r\nAddress of venue: Barnsley Road, Dodworth, Barnsley S75 3JT (just off Junction 37 of M1)","created":"2012-02-29 12:00:00","category_id":"1","img":"4539337","category":"General","fullname":"Tom Snee","user_id":"170458","image_user_id":"170458","image_file":"1330519210_0.jpg","image_width":"600","image_height":"848","sticky":"1","tagged_division_id":null,"tagged_team_id":null,"tagged_division":null,"tagged_team":null,"full_image":"http:\/\/images.pitchero.com\/up\/league-news-default-full.png","image_primary":"http:\/\/images.pitchero.com\/ui\/170458\/lnl_1330519210_0.jpg","image_secondary":"http:\/\/images.pitchero.com\/ui\/170458\/lns_1330519210_0.jpg","image_original":"http:\/\/images.pitchero.com\/ui\/170458\/1330519210_0.jpg","image_small":"http:\/\/images.pitchero.com\/ui\/170458\/sm_1330519210_0.jpg"}
heres my android code
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject obj = new JSONObject(json);
List<String> items = new ArrayList<String>();
Log.i("json", "getting json");
JSONArray jArray = obj.getJSONArray("news");
for (int i=0; i < jArray.length(); i++)
{ JSONObject oneObject = jArray.getJSONObject(i);
items.add(oneObject.getString("title"));
}
setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
}
});
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
}
I have tried logging it at LogCat gets the result no value for news.
so my question is why?
First of your json response is invalid.
You can test your JSON response at JSONLint.com
Second, first you have to fetch "data" object as a JSONObject and then you can able to fetch "news" JSONArray.
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("news");
Related
I tried to do it with multiple Shared Preferences keys, but it goes quiet complicated.
I saw some said that it is possible with JSON, but have no idea how to do it.
My app has many items in ListView, and I want to save several values in each item.
You can imagine a contact management app.
When the Item(person name) is clicked, you can check the values like phone number, address, and picture. And of course, they can be edited, added and deleted.
Is it possible to save values in single KEY with JSON?
So that I can load the values for each item when it is clicked.
To be able to save multiple values inside a jsonObject you can do this
try {
JSONObject Contacts = new JSONObject();
Contacts.put("Name", "Saul Goodman");
Contacts.put("Address", "Ocean Drive");
Contacts.put("Phone", "13456");
Contacts.put("Contacts", Contacts);
} catch (JSONException e) {
e.printStackTrace();
}
So that will create a structure like this
"Contacts":{
"Name":"Saul Goodman",
"Address":"Ocean Drive",
"Phone":"123456"
}
};
To retrieve this values you should do this
JSONArray array = object.getJSONArray("Contacts");
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
String name = object.get("Name");
String address = object.get("Address");
String phone = object.get("Phone");
//you also can use object.getString(""); to get the strings
}
hope it helps
Happy coding !
I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.
My Code is -
JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.
URL just gives a word like - done that's it not even " or : { nothing
Then simply use the String variable s , don't convert it into json
plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception
try{
// exception will be thrown in case of invalid json
JSONObject jsonObject = new JSONObject(s);
}
catch(JSONException e){
// s containing a single word so use it as it is
}
In my Android app, I'm trying to parse JSON data from a Google Places URL into a ListView. I'm trying to list the names of nearby restaurants. It appears that the parsing works, but I don't know how to grab the "name" variable out of the JSON data. The returned list has items in it that like this:
{"id":
"6217c344be105e............"
{"id":
"2c66bf813799zr2844......"
Which to me, looks like it's parsing the "id" variable in the Google Place URL's "results" array. I want it to grab the "name" variable in the "results" array. Can someone show me the correct code to do this? Here's the JSON parsing method that I'm using:
public void parseJSON() throws ClientProtocolException, IOException, JSONException
{
String bcURL="https://maps.googleapis.com/maps/api/place/search/json?"
+ "location=" + latString + "," + longiString
+ "&radius=15000&"
+ "types=restaurant&sensor=false&key="
+ myPlaceKey;
//--- Get Places URL ----
client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(bcURL));
int statusLine = response.getStatusLine().getStatusCode();
if(statusLine == 200){
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONObject urlData = new JSONObject(data);
JSONArray resultsArr = urlData.getJSONArray("results");
int length = resultsArr.length();
List<String> listContents = new ArrayList<String>(length);
for (int i = 0; i < length; i++)
{
listContents.add(resultsArr.getString(i));
}
ListView restListView = (ListView) findViewById(R.id.jsonList);
restListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents));
}
//--- END Get Places URL ----
and the listview part of the code:
JSONArray resultsArr = urlData.getJSONArray("results");
int length = resultsArr.length();
List<String> listContents = new ArrayList<String>(length);
for (int i = 0; i < length; i++)
{
listContents.add(resultsArr.getString(i));
}
ListView restListView = (ListView) findViewById(R.id.jsonList);
restListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents));
}
//--- END Get Places URL ----
where does the "get the name variable" bit of code go, and what would that code look like?
Take a look at here, it should describe everything you need.
Long story short: you need to retrieve from the jsonObject the value you need using JSONObject.getString("attributeName")
If you want to grab the first object of the JSON file you need to do something like this :
JSONArray samplearr = null;
samplearr = new JSONArray(String);
for(int index=0;index<samplearr.length();index++)
{
try
{
JSONObject obj = samplearr.getJSONObject(index);
JSONObject userobj = samplearr.getJSONObject(index).getJSONObject("user");
Log.d("object","sample array created");
userobj.getString("screen_name"),
obj.get("text").toString(),
userobj.getString("profile_image_url")
}catch(Exception er)
{
Log.d("exceptiom","exception found at : "+er.getMessage());
}
}
BAsically if you want to grab an object within an object then you do that. According to your question it seems the field you want is inside the "id" field so you have to parse two times through it
In the below code, I can display the first returned JSON place name result from my Google Places URL. Rather than just the first item, I'd like to display the whole returned list of place names. What would be the easiest way of doing this? Can you point me to a tutorial, or give sample code?
HttpGet get = new HttpGet(bcURL.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
json = new JSONObject(data);
JSONArray timeline = json.getJSONArray("results");
JSONObject lastport = timeline.getJSONObject(0);
return lastport;
}else{
Toast.makeText(NewGPS3.this, "oops", Toast.LENGTH_SHORT);
return null;
}
The line JSONObject lastport = timeline.getJSONObject(0); shows the first name. I'd like to show a list rather than just the first item.
You are going to need to use a JSONArray object in order to get at the array. It should go something like this:
JSONObject entireObject = new JSONObject("your JSON string here");
JSONObject mainObject = entireObject.getJSONObject("photos"); // main object in entire object
JSONArray arrayObject = mainObject.getJSONArray("photo"); // array object in the main object
You can then iterate through this array just like any other:
for (int i = 0; i < arrayObject.length(); i++) {
JSONObject photoData = arrayObject.getJSONObject(i);
String yourString = photoData.getString("id");
}
I got some of this out of Pro Android Media. There is a really good JSON api call example in this book. You can probably get the source code for free, too.
http://www.amazon.com/Pro-Android-Media-Developing-Smartphones/dp/1430232676/ref=sr_1_1?ie=UTF8&qid=1343062690&sr=8-1&keywords=android+media
for(int i = 0; i < timeline.size(); i++){
JSONObject lastport = timeline.getJSONObject(i);
//Save the item to a ArrayList and use that list for your ListAdapter.
googlePlaces.add(lastPort);
}
Hi i have a list i have it filling in a title from a Json Feed and now i want to add an image to it heres my single_list layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true" />
<TextView
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_gr_arrow"
android:id="#+id/textView1"
android:textColor="#color/blue"
android:padding="20dp"
android:textSize="10dp"
/>
</RelativeLayout>
heres the an example of one news story from the JSON Feed i think it image_small i need
{"code":200,"error":null,"data":{"news":[{"news_id":"8086","title":"Tickets for Player of the Year award on general sale","tagline":"Event to be held Sunday 25th March at Holiday Inn, Barnsley","content":"Tickets for the inaugural Evo-Stik NPL Player of the Year event are now on sale to the general public.\r\n\r\nPriced at \u00a335, tickets include a three course meal, plus entertainment from renowned tenor Martin Toal and guest speaker Fred Eyre.\r\n\r\nAwards at the event include the Player and Young Player of the Year for each division, as well as divisional teams of the year, the Fans\u2019 Player of the Year and a League Merit award.\r\n\r\nTo purchase your ticket, send a cheque for \u00a335 payable to \u201cNorthern Premier League\u201d to Alan Ogley, 21 Ibberson Avenue, Mapplewell, Barnsley, S75 6BJ. Please include a return address for the tickets to be sent to, and the names of those attending. \r\n\r\nFor more information, e-mail Tom Snee or contact Event organiser Alan Ogley on 07747 576 415\r\n\r\nNote: Clubs can still order tickets by e-mailing Angie Firth - simply state how many tickets you require and you will be invoiced accordingly.\r\n\r\nAddress of venue: Barnsley Road, Dodworth, Barnsley S75 3JT (just off Junction 37 of M1)","created":"2012-02-29 12:00:00","category_id":"1","img":"4539337","category":"General","fullname":"Tom Snee","user_id":"170458","image_user_id":"170458","image_file":"1330519210_0.jpg","image_width":"600","image_height":"848","sticky":"1","tagged_division_id":null,"tagged_team_id":null,"tagged_division":null,"tagged_team":null,"full_image":"http:\/\/images.pitchero.com\/up\/league-news-default-full.png","image_primary":"http:\/\/images.pitchero.com\/ui\/170458\/lnl_1330519210_0.jpg","image_secondary":"http:\/\/images.pitchero.com\/ui\/170458\/lns_1330519210_0.jpg","image_original":"http:\/\/images.pitchero.com\/ui\/170458\/1330519210_0.jpg","image_small":"http:\/\/images.pitchero.com\/ui\/170458\/sm_1330519210_0.jpg"}
and heres my code so far
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject obj = new JSONObject(json);
List<String> items = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("news");
for (int i=0; i < jArray.length(); i++)
{ JSONObject oneObject = jArray.getJSONObject(i);
items.add(oneObject.getString("title"));
Log.i("items", "items");
}
setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
}
});
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
I assume you want to load Image for every items in your listview, if this is the case then you can implement any solution from below:
Lazy load of images in ListView
Android Universal Image Loader by Nostra.