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

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

Related

How to parse nested Objects in android to readable html

I have this code from JSONParser.java
try{
JSONArray postArray = jsonObject.getJSONArray("posts");
// Go through each post
for (int i = 0; i < postArray.length(); i++) {
JSONObject postObject = postArray.getJSONObject(i);
Post post = new Post();
post.setCfs(postObject.getJSONObject("custom_fields").optString("entity", "N/A"));
that displays this
["Some text"]
I want it to display without [" and "]
My Json for that specific part is as below
"posts":[{
"date":"2016-02-10 10:28:42",
"categories":[{}],
"tags":[],
"author":{"name":"admin"},
"custom_fields":{
"ref_number":["ITB NUMBER: ITB\/002\/2016"],
"deadline":["26 February, 2016"],
"entity":["Refugees (xxx)"]
}
It seems that "entity" is array and you should try something like that:
post.setCfs(postObject.getJSONObject("custom_fields").optJSONArray("entity").getString(0));

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[]

JSONObject or JSONArray

I have data on this string, but I'm having trouble to access the individual data.
This is my code:
Log.d("Detail Outputss", "" + response.toString());
And this is the string output:
{"futsal_id":"45","info":[{"futsal_id":"45","futsal_name":"Kathmandu Futsal","city":"Kathmandu","address":"Kathmandu","owner_name":"Hari Prasad","owner_address":"Kathmandu","email":"kathmandufutsal#gmail.com","password":"kathmandu","phone_no":"1111111","mobile_no":"9841112233","status":"1"}],"description":[{"futsal_id":"45","futsal_desc":"Futsal is the fever which never ends.\r\nKathmandu futsal is - a platform, a medium of communication for our fraternity. Not just somewhere to host challenges or seek venues, but a place where we can all share and spread the luv! Here, you can find just about anything, do just about anything, and see just about anything. Unbelievable? Believe it."}],"features":[{"futsal_id":"45","futsal_feat":"Free Wifi"},{"futsal_id":"45","futsal_feat":"High Quality Grass"},{"futsal_id":"45","futsal_feat":"Canteen Facility"},{"futsal_id":"45","futsal_feat":"Friendly Environment"}],"dimension":[{"futsal_id":"45","dimension":"40m X 20m"}],"no_of_futsal":[{"futsal_id":"45","number":"1"}],"opening_hrs":[{"futsal_id":"45","open_time_id":"1","open_time":"6am","close_time_id":"15","close_time":"9pm"}],"price_weekdays_price1":[{"futsal_id":"45","price_id":"1","start_time":"6am","end_time":"12pm","price":"1200"}],"price_weekdays_price2":[{"futsal_id":"45","price_id":"2","start_time":"12pm","end_time":"6pm","price":"1000"}],"price_weekdays_price3":[{"futsal_id":"45","price_id":"3","start_time":"6pm","end_time":"9pm","price":"1500"}],"price_weekend_price1":[{"futsal_id":"45","price_id":"1","start_time":"6pm","end_time":"12pm","price":"1500"}],"price_weekend_price2":[{"futsal_id":"45","price_id":"2","start_time":"12pm","end_time":"6pm","price":"1800"}],"price_weekend_price3":[{"futsal_id":"45","price_id":"3","start_time":"6pm","end_time":"9pm","price":"2000"}],"phone_number_address":[{"futsal_id":"45","futsal_name":"Kathmandu Futsal","city":"Kathmandu","address":"Kathmandu","owner_name":"Hari Prasad","owner_address":"Kathmandu","email":"kathmandufutsal#gmail.com","password":"kathmandu","phone_no":"1111111","mobile_no":"9841112233","status":"1"}],"news":[{"futsal_id":"45","news_id":"7","news_title":"asdfasdfasdfasdf","news_description":"asdfashdflahsdlfasdjf;oajsd;ofjaosdijfoaisdjofajsdfja;sjdf;ajsd;fja;ksdjf;kasjd;fkja;sdjf;asjd;fajsd;fjasdjf;asjd;fjas;djf;asdf"},{"futsal_id":"45","news_id":"6","news_title":"awefasdf","news_description":"sdjf;asdf;a;sdf;asjdf;oajsd;fja;sdjf;oajsd;oifjaosdf"},{"futsal_id":"45","news_id":"5","news_title":"asdfasdf","news_description":"sadfasdfasdfasdfa"}]}
I want to get the value of each object futsal_id, futsal_name, city and others, thanks in advance!!
It is JSONArray within a JSONObject
JSONObject json = new JSONObject(response);
JSONArray info = json.getJSONArray("info");
//getting the first value.. loop it if you have more than one
JSONObject infoObject = info.getJSONObject(0);
JSONArray description = json.getJSONArray("description");
JSONObject json = new JSONObject(response);
int fustal_id =Integer.parseInt(json.getString("futsal_id"));
JSONArray inf = json.getJSONArray("info");
JSONObject info = inf.getJSONObject(0);
...
JSONObject responseObject = new JSONObject(response);
JSONArray info = responseObject.getJSONArray("info");
for(int i = 0; i < info.length(); i++) {
JSONObject obj = info.getJSONObject(i);
String futsal_id = obj.getString("futsal_id");
String futsal_name = obj.getString("futsal_name");
//so on
}
Be sure to catch the exceptions.

How to Extract json array within an array in android

I am trying to pass some json encoded data from cakephp to android, I have a problem when passing the data
I use
echo json_encode($todaysdata);
exit();
in CakePhp and when I debug this code in cakephp, I get a result in the browser
[{"status":{"uname":"sibin","pass":"shanu","upid":14}},
{"status": {"uname":"amal","pass":"amalu","upid":14}}
]
I need to extract these two status details seperately in Android
I tried one code in android, it gives result, but result is repeated
I want the result of two status seperately
If anybody know, please help me.
set status value as from current json String :
JSONArray jsonarr = new JSONArray("your json String");
for(int i = 0; i < jsonarr.length(); i++){
JSONObject jsonobj = jsonarr.getJSONObject(i);
// get status JSONObject
JSONObject jsonobjstatus = jsonobj.getJSONObject("status");
// get uname
String str_uname=jsonobjstatus.getString("uname");
// get pass
String str_pass=jsonobjstatus.getString("pass");
// get upid
String str_upid=jsonobjstatus.getString("upid");
}
Try with the following code.
JSONArray jsonArray = new JSONArray("yourJsonResponseInString");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject e = jsonArray.getJSONObject(i);
JSONObject jsonObject = e.getJSONObject("status");
Log.i("=== UserName","::"+jsonObject.getString("uname"));
Log.i("=== Password","::"+jsonObject.getString("pass"));
Log.i("=== UId","::"+jsonObject.getString("upid"));
}

In Android, parsing Google places URL into a ListView?

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

Categories

Resources