I have a json parse like this
public class SecondFragment extends Fragment implements OnClickListener {
// URL to get contacts JSON
private static String contestUrl = "http://api.apps.com/contest";
// JSON Node names
private static final String TAG_ITEM_ID = "id";
private static final String TAG_URL = "url";
private static final String TAG_START_DATE = "start_date";
private static final String TAG_END_DATE = "end_date";
// contacts JSONArray
JSONArray foods = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> foodslist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
foodslist = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(contestUrl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
String start_date = (String)contact.get(TAG_ITEM_ID);
// adding contact to contact list
foodslist.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
}
I have two function, onCreate and GetContacts. In the end of onCreate it call GetContacts and call this json.
My question is, how can I got the Hashmap value on GetContacts so I can use it on onCreate
So far, I got this to get the value of Hashmap
String start_date = (String)contact.get(TAG_ITEM_ID);
But, its only works on GetContacts.
Anyone can help me?
Thanks Before
There are couple of ways:
Way-1:
Create instance variable (class-level) of HashMap contact and then you can use it anywhere within class inclusing onCreate and getContacts method.
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
private static Map<String, String> contact = new HashMap<String, String>();
public void onCreate() {
//populate contact object as per your logic
getContacts();
}
private void getContacts() {
//Use contact object directly which was pre-populby onCreate method.
}
}
Way-2:
Pass map to the getContacts() method:
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
public void onCreate() {
final Map<String, String> contact = new HashMap<String, String>();
//populate contact object as per your logic.
getContacts(contact);
}
private void getContacts(Map<String, String> contact) {
//Use contact object which is passed as argument.
}
}
On other side, please use cameCasing while naming Java methods or variables. GetContacts is not right, make it getContacts.
For email and address fields, using TAG_START_DATE and TAG_END_DATE is no fun. :-)
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
To answer about #3 below, variable s is not accessible in NotInner class:
package com.test;
public class Test {
static String s = "";
}
class NotInner {
public static void main(String[] args) {
System.out.println(s); //Compilation error: s cannot be resolved to a variable
}
}
You have
List<Map<String,String>> foodslist = ...;
which is filled in the loop.
To get at individual values, iterate:
for( Map<String,String> item: foodslist ){
String id = item.get(TAG_ITEM_ID);
String name = item.get(TAG_URL);
String email = item.get(TAG_START_DATE);
String address = item.get(TAG_END_DATE);
}
Or you write a method for the class where you keep foodslist:
String getAttr( int i, String tag ){
return foodslist.get(i).get(tag);
}
and you can call
String id = xxx.getAttr( i, TAG_ITEM_ID );
So return the data ...
public List<Map<String, String>> getContacts() {
if (foodslist != null && foodslist.isEmpty()) {
return foodslist;
}
foodslist = new ArrayList<Map<String, String>>();
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
// adding contact to contact list
foodslist.add(contact);
}
return foodslist;
}
Though I'm not sure why that variable is called foodslist if it's supposed to contain contacts.
Related
I have data of tracks & tracklinks like folowing:
trackname - abc
links - www.abc.com
www.abc1.com
www.abc2.com
trackname - xyz
links - www.xyz.com
www.xyz1.com
www.xyz2.com
I want to make array with in array in Java. so final array would be:
trackdata = {
[0] {
[trackname] = 'abc',
[tracklinks] = {
[0] = "www.abc.com";
[1] = "www.abc1.com";
[2] = "www.abc2.com";
}
},
[1] {
[trackname] = 'xyz',
[tracklinks] = {
[0] = "www.xyz.com";
[1] = "www.xyz1.com";
[2] = "www.xyz2.com";
}
}
I have tried to make this using ArrayList, Map but not succeed.
Map<String,String> map = new HashMap<>();
map.put("trackname", "abc");
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("tracklinks", myLinks);
please help me here.
Consider using a multimap, a map whose values are list objects:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Starter {
public static void main(String[] args) {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("abc", myLinks);
System.out.println(map); // {abc=[www.abc.com, www.abc1.com, www.abc2.com]}
}
}
You should create a class and then access the properties like you want.
class TrackData {
private String trackme;
private List<String> trackLink;
public String getTrackme() {return trackme;}
public void setTrackme(String trackme) {this.trackme = trackme;}
public List<String> getTrackLink() {return trackLink;}
public void setTrackLink(List<String> trackLink) {this.trackLink = trackLink;}
}
To access it:
#Test
void arrayInArray_Test1() {
List<TrackData> trackData = new ArrayList<>();
trackData.add(new TrackData(){{
setTrackme("abc");
setTrackLink(new ArrayList<String>(){{
add("www.abc.com");
add("www.abc1.com");
add("www.abc2.com");
}});
}});
trackData.add(new TrackData(){{
setTrackme("xyz");
setTrackLink(new ArrayList<String>(){{
add("www.xyz.com");
add("www.xyz1.com");
add("www.xyz2.com");
}});
}});
System.out.println(trackData);
}
If you are using a newer Java version, you can create a record instead of a class.
You can achieve as follows
public class TrackTest {
public static void main(String[] args) {
List<Tracks> trackList = new ArrayList<>();
Tracks track1 = new Tracks("abc");
track1.getTrackLinks().add("www.abc.com");
track1.getTrackLinks().add("www.abc1.com");
track1.getTrackLinks().add("www.abc2.com");
Tracks track2 = new Tracks("xyz");
track2.getTrackLinks().add("www.xyz.com");
track2.getTrackLinks().add("www.xyz1.com");
track2.getTrackLinks().add("www.xyz2.com");
trackList.add(track1);
trackList.add(track2);
System.out.println(trackList);
}
static class Tracks{
private String trackName;
private List<String> trackLinks;
public Tracks(String trackName) {
this.trackName = trackName;
this.trackLinks = new ArrayList<>();
}
public Tracks(String trackName, List<String> trackLinks) {
this.trackName = trackName;
this.trackLinks = trackLinks;
}
public String getTrackName() {
return trackName;
}
public List<String> getTrackLinks() {
return trackLinks;
}
#Override
public String toString() {
return "Tracks [trackName=" + trackName + ", trackLinks=" + trackLinks + "]";
}
}
}
Let me know, if you want other approach.
how are u?
Why u dont do this.
Create class named URL, for example.
public class Url(){
//atributes
String domain;
String url;
//Contructor
public class URL(String domain, String url){
this.domain = domain;
this.url = url;
}
}
In ur main.class, u can create one Arraylist to saves ur instaces of URL.
public static void newURL(){
String domain, url;
Scanner keyboard = new Scanner(System.in);
//ask domain, i will use an example.
System.out.println("What is domain of URL?");
domain = keyboard.nextLine();
System.out.println("What is url?");
url = keyboard.nextLine;
//now, u have atributes of new url
URL url = new URL(domain,url);
}
What its ur objective? It's important question.
If is for simple control in a little program, u can do this
I try to get number of post from arraylist in the class into mainactivity.
But it is wrong .
Here is my code.
public static int countNotify;
public static List<Notification> bindNotifyData(JsonElement list)
{
List<Notification> results= new ArrayList<>();
JsonObject dataJsonObj = list.getAsJsonObject();
// get data api from Json array "updates"
JsonArray notifyJsonArray = dataJsonObj.get("updates").getAsJsonArray();
ArrayList<Notification> notifyList = new ArrayList<>();
countNotify=notifyJsonArray.size();
if(notifyJsonArray != null && notifyJsonArray.size() > 0) {
for(int i = 0; i < notifyJsonArray.size(); i++) {
JsonObject notifyJson = (JsonObject) notifyJsonArray.get(i);
Notification notification = new Notification();
notification.setContent(notifyJson.get("content").getAsString());
// Convert timestamp to Datetime
String timestamp= notifyJson.get("time").getAsString();
notification.setTime(ConvertTimestamp(timestamp));
results.add(notification);
// count numbers of the post in the list json array.
}
}
return results;
}
And in the MainActivity.class
final int count=BindFetchDataHelper.countNotify;
But the value of count always is 0
Try to create a instance of your class
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
and then call final int count=bindFetchDataHelper.countNotify;
I had the same issue, it should work now.
EDIT
Try like this :
public class BindFetchDataHelper {
private static int sTest;
static {
public static int countNotify=0;
}
public static int getcountNotify() {
return countNotify;
}
public static void setcountNotify(int setcountNotify) {
this.countNotify = countNotify;
}
//your others functions
}
And now to access variable or to set it :
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
bindFetchDataHelper.setcountNotify(YOURVALUE); //set
int whatyourwant = bindFetchDataHelper.getcountNotify(); //get
i have this webservice:
[WebMethod]
public string findUserNameById(int Id)
{
return getStudent(Id);
}
public String getStudent(int id)
{
SqlConnection conn;
conn = Class1.ConnectionManager.GetConnection();
conn.Open();
SqlCommand newCmd = conn.CreateCommand();
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "select * from dbo.tblUser where Id=" + id + "";
SqlDataReader sdr = newCmd.ExecuteReader();
String address = null;
if (sdr.Read())
{
address = sdr.GetValue(0).ToString();
address += "," + sdr.GetValue(1).ToString();
address += "," + sdr.GetValue(2).ToString();
}
conn.Close();
return address;
}
which retrieve row values like this: Id, name, grade. and im calling this webservice from android application:
public class MainActivity extends AppCompatActivity {
private EditText editText;
private TextView textView;
private Handler mHandler= new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
textView = (TextView)findViewById(R.id.textView);
}
public void getName(View v){
String inputId =editText.getText().toString();
//String[] params= new String[]{"10.0.2.2",inputId};
String[] params= new String[]{"192.168.1.17:90",inputId};
new MyAsyncTask().execute(params);
}
class MyAsyncTask extends AsyncTask<String, Void, String>
{
public String SOAP_ACTION="http://tempuri.org/findUserNameById";
public String OPERATION_NAME ="findUserNameById";
public String WSDL_TARGET_NAMESPACE ="http://tempuri.org/";
public String SOAP_ADDRESS;
private SoapObject request;
private HttpTransportSE httpTransport;
private SoapSerializationEnvelope envelop;
Object response= null;
#Override
protected String doInBackground(String... params) {
SOAP_ADDRESS="http://"+params[0]+"/myWebService.asmx";
request= new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("Id");
pi.setValue(Integer.parseInt(params[1]));
pi.setType(Integer.class);
request.addProperty(pi);
pi= new PropertyInfo();
envelop= new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelop.dotNet=true;
envelop.setOutputSoapObject(request);
httpTransport=new HttpTransportSE(SOAP_ADDRESS);
try{
httpTransport.call(SOAP_ACTION,envelop);
response=envelop.getResponse();
}
catch (Exception e){
response=e.getMessage();
}
return response.toString();
}
#Override
protected void onPostExecute(final String result){
super.onPostExecute(result);
mHandler.post(new Runnable() {
#Override
public void run() {
textView.setText(result);
}
});
}
}
I want to fetch all of the rows and display it in a list view in the android, how to do it?
the query will be like : select * from dbo.tblUser
what should i change in the webservice? also what should i do in java for android?
try this code-
SoapObject response = (SoapObject) envelope.getResponse();
yourArray=new String[response.getPropertyCount()];
for(int i=0;i<response.getPropertyCount();i++){
Object property = response.getProperty(i);
if(property instanceof SoapObject){
SoapObject final_object = (SoapObject) property;
yourArray[i] = final_object.getProperty("YOUR_PROPERTY_NAME");
}
}
I would recommend that you declare your MainAsyncTask like this:
public class MainAsyncTask extends AsyncTask<String, Void, String[]> {
Then modify doInBackground to do all the processing that you are now doing in onPostExecute (except for the Toast part if any) and have it return the String[] (or null if there's an error). You can store the result code in an instance variable of MainAsyncTask and return null on error. Then onPostExecute has access to the same info that it does with your current code. Finally, if there is no error, just call a method in your main activity from onPostExecute to do the UI updates, passing it the String[] result.
Declare one POJO -
class AllocatedData{
String Id, name, grade;
getters and constructor
}
Code -
List<AllocatedData> list = new ArrayList<AllocatedData>();
if (responseLevel4 != null) {
for(int i = 0; i < responseLevel4.getPropertyCount(); i++){
responseLevel5 = (SoapObject) responseLevel4.getProperty(i);
Data allocated = new AllocatedData(checkStringProperty("Id"),checkStringProperty("name"),
checkStringProperty("grade"));
list.add(allocated);
}
}
}
Which function handles if property is Null
public String checkStringProperty(String propertyName){
if(responseLevel5.hasProperty(propertyName)){
return responseLevel5.getProperty(propertyName).toString();
} else {
return null;
}
}
But my Suggestion is use JSON reponse Or generate response in JSON.
I tried it before in Asp.net web services in which difficult to generated JSON. try WCF services
Link :- http://www.codeproject.com/Articles/167159/How-to-create-a-JSON-WCF-RESTful-Service-in-sec
By Using json you can parse directly by GSON liabrary this is very fast as compate to SOAP.
Gson gson = new Gson();
for (int i = 0; i < array.length(); i++) {
AllocatedData app = gson.fromJson(array.getJSONObject(i).toString(), AllocatedData .class);
list.add(app);
}
I would suggest you to create a Model Class which holds all the Property you need to send back
Public class Address{
public int grade;
public String name;
public String grade;
}
Create List<Address> addressList;
Iterate through the result set you get from database and in each iteration create a address object and put it in List and return List as response
Edit
Android Side reading from list you can refer this link
http://seesharpgears.blogspot.in/2010/10/web-service-that-returns-array-of.html
SERVICE SIDE
Instead of this Line
if (sdr.Read())
{
address = sdr.GetValue(0).ToString();
address += "," + sdr.GetValue(1).ToString();
address += "," + sdr.GetValue(2).ToString();
}
change it to
List<Address> addressList=new ArrayList<Address>();
while (sdr.Read())
{
Address address=new Address();
address.id = sdr.GetValue(0);
address.name= sdr.GetValue(1).ToString();
address.grade=sdr.GetValue(2).ToString();
addressList.add(address);
}
return addressList;
I have a LinkedHashMap which fills with data from db with loop "for" string by string and when I try to show the first or the last String, the method can show me only the last String in log. But in application listViewContent is filled fully. So I don't understand why I can't see any string that I want. I need to collect all strings I get from db and compare them in future.
How can I collect all strings and what method should I call to show the string I want to see?Unfortunately I can only retrieve one (and the last instead of the first) string.
Here is my example code :
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FirstMethod();
}
public FirstMethod() {
SecondMethod newMethod = .. // getting data from the second method
}
public SecondMethod() {
public void onResponseReceived(String result) {
try {
...
if (posts != null) {
for (WallPostItem post : posts) { // this loop
//create new map for a post
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put(ATTRIBUTE_NAME_TEXT, post.text);
PictureItem postPicture = new PictureItem();
map.put(ATTRIBUTE_NAME_IMAGE, postPicture);
map.put(ATTRIBUTE_NAME_DATE, post.date);
sAdapter.notifyDataSetChanged();
};
};
...
List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(GlobalMap.entrySet());
Map.Entry<String, Object> firstInsertedEntry = list.get(0);
Log.w("FirstEntryOfMap",""+firstInsertedEntry); // this log shows me the last string instead of the first
}
if (isRefresh) {
isRefresh = false;
lvSimple.setSelectionAfterHeaderView();
}
} catch (Exception e) {
Log.d("exceptions", "problem in get wall post task after post execute: " + e.toString());
}
}
You aren't putting your values into a List, you are putting them into a Map (that preserves key order). I would suggest you create a POJO class,
class MyAttribute {
final String postName;
final PictureItem postPicture;
final Date postDate;
public MyAttribute(String postName, PictureItem postPicture, Date postDate) {
this.postName = postName;
this.postPicture = postPicture;
this.postDate = postDate;
}
public String getPostName() {
return postName;
}
public Date getPostDate() {
return postDate;
}
public PictureItem getPostPicture() {
return postPicture;
}
}
Then you could create a
List<MyAttribute> myAttributes = new ArrayList<>();
I have been trying to extract the goolge places api photo reference but have not had any success. I was wondering if someone could help me. Below is my code:
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
public static String KEY_PHOTO = "photo_reference";
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* getting google places JSON response
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
String types = MenuActivity.type;
String keyword = MenuActivity.keyword;
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),gps.getLongitude(),
types, keyword);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get JSON response status
String status = nearPlaces.status;
// Check for OK status
if (status.equals("OK")) {
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
map.put(KEY_PHOTO,p.photo);
map.put(KEY_VICINITY, p.vicinity);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter - removed rating
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, placesListItems,
R.layout.list_item, new String[] {
KEY_REFERENCE, KEY_NAME, KEY_VICINITY, KEY_PHOTO},
new int[] { R.id.reference, R.id.name, R.id.address, R.id.phptp});
// Adding data into ListView
lv.setAdapter(adapter);
}
}
}
Below is my code that performs the search and parses the data:
public class GooglePlaces {
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final String LOG_KEY = "GGPlace";
// Google API Key
private static final String API_KEY = "";
// Google Places serach
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&rankby=distance";
private double _latitude;
private double _longitude;
private double _radius;
private String address;
public PlacesList search(double latitude, double longitude, String types, String keyword)
throws Exception {
this._latitude = latitude;
this._longitude = longitude;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", _latitude + "," + _longitude);
request.getUrl().put("sensor", "true");
if(types != null)
{
request.getUrl().put("types", types);
request.getUrl().put("keyword", keyword);
}
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
public static HttpRequestFactory createRequestFactory(
final HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("APP NAME");
headers.gdataVersion="2";
request.setHeaders(headers);
JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
request.addParser(parser);
}
});
}
}
This is my PlaceList class:
public class PlacesList implements Serializable {
#Key
public String status;
#Key
public List<Place> results;
}
Here is my Place class:
public class Place implements Serializable {
#Key
public String id;
#Key
public String name;
#Key
public String reference;
#Key
public String vicinity;
#Key
public Geometry geometry;
#Key
public List<Photo> photos;
}
And finally my Photo class:
public class Photo implements Serializable {
#Key
public String photo_reference;
#Key
public int height;
#Key
public int width;
}
I guess I am calling or passing the photo_reference the wrong way. I am hoping there is someone out there that can help me out. I've been working on this for weeks and have almost completely given up.
Hi firstly your search url is wrong.
You have to follow this format:
https://developers.google.com/places/web-service/photos
Please see below for a complete example:
http://wptrafficanalyzer.in/blog/showing-nearby-places-with-photos-at-any-location-in-google-maps-android-api-v2/
If you download the source code, it will help you see how to fetch the json string in an array which is in another array.
The snippet below just answers the part where you have to fetch the image:
package in.wptrafficanalyzer.locationnearbyplacesphotos;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public Place[] parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private Place[] getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
Place[] places = new Place[placesCount];
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
places[i] = getPlace((JSONObject)jPlaces.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return places;
}
/** Parsing the Place JSON object */
private Place getPlace(JSONObject jPlace){
Place place = new Place();
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
place.mPlaceName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
place.mVicinity = jPlace.getString("vicinity");
}
if(!jPlace.isNull("photos")){
JSONArray photos = jPlace.getJSONArray("photos");
place.mPhotos = new Photo[photos.length()];
for(int i=0;i<photos.length();i++){
place.mPhotos[i] = new Photo();
place.mPhotos[i].mWidth = ((JSONObject)photos.get(i)).getInt("width");
place.mPhotos[i].mHeight = ((JSONObject)photos.get(i)).getInt("height");
place.mPhotos[i].mPhotoReference = ((JSONObject)photos.get(i)).getString("photo_reference");
JSONArray attributions = ((JSONObject)photos.get(i)).getJSONArray("html_attributions");
place.mPhotos[i].mAttributions = new Attribution[attributions.length()];
for(int j=0;j<attributions.length();j++){
place.mPhotos[i].mAttributions[j] = new Attribution();
place.mPhotos[i].mAttributions[j].mHtmlAttribution = attributions.getString(j);
}
}
}
place.mLat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
place.mLng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
} catch (JSONException e) {
e.printStackTrace();
Log.d("EXCEPTION", e.toString());
}
return place;
}
}
I first misunderstood photo_reference as Base64 Encoded String. But it is not indeed it is a reference parameter to identify and fetch a photo from google maps API. Imagine this as a token parameter. So to fetch a photo with max-width 400 you can use below URL.
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=YOUR_API_KEY
For more details visit Google Places documentation
https://developers.google.com/places/web-service/photos