In Android, parsing Google places URL into a ListView? - android

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

Related

Convert json object into multiple arrays android

I have a json object being downloaded from my server that returns a result in the following format:
{"Bookname":["Alive-O","All Write Now ","Bun Go Barr 1","Planet Maths","Small World"],"SubjectName":["Religion","English","Irish","Maths","Science"]}
What I want to do is turn that into two different arrays to use on the android device.
Here is the request and the looking for the response within my asynctask
String[] BookName;
String[] BookSubject;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
}
Just wondering how I store the above result in the two arrays?
It would be something like this
JSONObject jsonObject = new JSONObject(result);
// for getting booknames
JSONArray jsonArray = jsonObject.getJSONArray("Bookname");
bookName = new String[jsonArray.length()]
for (int i = 0; i < jsonArray.length(); i++) {
bookName[i] = jsonArray.getString(i);
}
// for getting subjectnames
jsonArray = jsonObject.getJSONArray("SubjectName");
bookSubject = new String[jsonArray.length()]
for (int i = 0; i < jsonArray.length(); i++) {
bookSubject[i] = jsonArray.getString(i);
}
Hope it will help..!!
Given that you chose JSONObject, that your JSON is that unusual structure, and that you want to mirror that structure in your Java:
Step #1: Call getJSONArray() on jObject() twice, to get the two JSONArray objects (Bookname and SubjectName)
Step #2: Allocate each String[] to be the proper length (call length() on the JSONArray)
Step #3: For each JSONArray, loop over the array indices (0 to length()) and call getString() for each index, assigning it to the appropriate index in the associated String[]

How to get array number JSON android

I have JSON :
{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}
My code :
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
products = json.getJSONArray("elements");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int ids = c.getInt(TAG_PID);
String id = String.valueOf(ids);
if (id.compareTo(id_kh) == 0) {
object = c.getJSONObject("links");
JSONArray courses = object.getJSONArray("courses");///???????????
//result = courses.split("[,]");
Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I dont know to get array number after "courses".
I would use HashMaps. Here you have an example (creating Hashmap from a JSON String
) how to get it from a JSON String.
Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>
courses is a JSONArray, so you can do like that:
JSONArray coursesArray = linksObject.getJSONArray("courses");
UPDATE:
To get values from coursesArray :
int value = coursesArray.optInt(position);
Almost there. Once you get your
JSONArray courses = object.getJSONArray("courses");
simply iterate over its values:
// you wanted these numbers in an array
// so let's create one, with size being number of elements in
// JSONArray courses
int[] courseIds = new int[courses.length()];
for (int j=0; j<courses.length(); j++) {
// assign current number to the appropriate element in your array of ints
coursesId[j] = courses.getInt(j);
Log.d("TAG", "number: " + number);
}
The above will save these numbers in an array and print them too:
number: 15
number: 30
number: 46
number: 47
Just keep in mind that "courses" key might not exist, the array might be empty etc.

parse json file from SD card in android app

I have an array of JSON objects on an SD card.
I get the file contents like this:
File yourFile = new File("/mnt/extSdCard/test.json");
FileInputStream stream = new FileInputStream(yourFile);
String jString = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
jString = Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
The structure is like this:
[{"name":"john"},{"name":"fred"},{"name":"sam"}]
and I want to be able to parse them to make a listView. In JavaScript I can get them as an AJAX request and then do
var people = JSON.parse(data.responseText);
and then loop through the array. But I am a complete novice at java - I have found example code that does each of those things separately but I can't put them all together. Any help much appreciated.
The problem is that the above JSON structure represents a JSONArray and not a JSONObject
JSON Syntax
So after getting your jstring just do this
JSONArray array = new JSONArray(jString);
for(int i=0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
String value = obj.getString("name");
}
If you have it as a string, you should be able to parse it to a JSONObject with something like this:
JSONObject jObj = null;
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.i(TAG, "JSON Data Parsed: " + jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
I would also put the data (in your example) into an array, so it appears as something like:
{"names": [{"name": "john"},{"name": "fred"},{"name": "sam"}]}
And then to read your object again, you can put it into an array (or something else I guess) with something like this:
// create an empty list
ArrayList<String> l = new ArrayList<String>();
// pull the array with the key 'names'
JSONArray array = jObj.getJSONArray("names");
// loop through the new array
for(int i = 0; i < array.length(); i++){
// pull a value from the array based on the key 'name'
l.add(array.getJSONObject(i).getString("name"));
}
Hope at least some of this helps out (or at least points you in the correct direction). There are PLENTY of resources on here though, too.
EDIT:
Read up on JSON formatting. [] denotes array and {} denotes object, so you have an array of objects. That is why I recommended changing your format. If you are set on your format, either go with what Mr.Me posted for his answer, or just split your string at special characters and put them into an array that way.
Try this
String[] from = new String[] {"name"};
int[] to = new int[] { R.id.name};
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
try
{
JSONArray names = new JSONArray(jsonString);
Log.i("MyList","Number of names " + names.length());
for (int j = 0; j < names.length(); j++)
{
JSONObject jsonObject = names.getJSONObject(j);
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", jsonObject.getString("name"));
fillMaps.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
}
SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
mListView.setAdapter(adapter);
Here mListView is your predefined ListView.
Feel free to share your doubts here, if any.

In Android, display Google Places JSON data in a list?

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

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources