In my app it's possibile to insert markers with touch and then it's possible to calculate the path through these markers with subsequent HTTP requests.
The issue is that very often the first markers is skipped and between the last two markers is drawn a segment too.
Here's the code:
public class MultipleTracksDrawer extends AbstractDrawer {
private static final String TAG_LOG = MultipleTracksAsyncTask.class.getName();
private boolean flag = false;
void draw() {
for(int i = 0; i < markers.size() - 1; i++) {
Marker firstMarker = markers.get(i);
Marker secondMarker = markers.get(i + 1);
//I extract latitude and longitude from the markers
LatLng firstLatLng = new LatLng(firstMarker.getPosition().latitude, firstMarker.getPosition().longitude);
LatLng secondLatLng = new LatLng(secondMarker.getPosition().latitude, secondMarker.getPosition().longitude);
//Url for the request
String URL = Utilities.getInstance().makeURL(firstLatLng.latitude, firstLatLng.longitude,
secondLatLng.latitude, secondLatLng.longitude, travelMode);
//At the end of the markers list i set the flag as true for draw the path
if(i == markers.size() - 2) {
flag = true;
}
MultipleTracksAsyncTask multipleTracksAsyncTask = new MultipleTracksAsyncTask(URL);
multipleTracksAsyncTask.execute();
}
}
private class MultipleTracksAsyncTask extends AsyncTask<Void,Void,String> {
private ProgressDialog mDialog;
private String URL;
public MultipleTracksAsyncTask(String URL) {
this.URL = URL;
}
protected void onPreExecute() {
mDialog = ProgressDialog.show(context, "", "Loading...", true);
}
protected void onPostExecute(String result) {
if(mDialog != null) {
if(mDialog.isShowing()) {
mDialog.dismiss();
}
}
if(result != null) {
parseJSON(result);
//I draw the path only if the flag is true
if(flag) {
drawPath();
}
}
}
public String doInBackground(Void... param) {
JSONRequest jParser = new JSONRequest();
String json = jParser.getJSONFromUrl(URL,connectionTimeout,dataTimeout);
return json;
}
}
private void parseJSON(String result) {
try {
final JSONObject json = new JSONObject(result);
//I get "routes" array
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONArray legsArray = routes.getJSONArray("legs");
JSONObject legsObject = legsArray.getJSONObject(0);
//I get distance and duration of the path
JSONObject distance = legsObject.getJSONObject("distance");
JSONObject duration = legsObject.getJSONObject("duration");
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
//Decoding
model.getMarkersTrack().addAll(Utilities.getInstance().decodePoly(encodedString));
mTrackDistance += distance.getInt("value");
mTrackDuration += duration.getInt("value");
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "The path is not available", Toast.LENGTH_SHORT).show();
}
}
private void drawPath() {
for(int i = 0; i < model.getMarkersTrack().size() - 1; i++) {
LatLng src = model.getMarkersTrack().get(i);
LatLng dest = model.getMarkersTrack().get(i + 1);
PolylineOptions polylineOptions = new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(5)
.color(Color.BLUE).geodesic(true);
Polyline polyline = googleMap.addPolyline(polylineOptions);
//I save the polylines
model.getTrackPolylines().add(polyline);
}
}
}
I put here the code for the HTTP request too:
public class JSONRequest {
private InputStream is = null;
private String json = "";
/**
* Method that makes the HTTP request
*
* #param url URL of the HTTP request
* #param connectionTimeout timeout for the connection
* #param dataTimeout timeout for the download
* #return
*/
public String getJSONFromUrl(String url, int connectionTimeout, int dataTimeout) {
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParams, dataTimeout);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
//GET request
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
//I get the response
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
//I read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
}
Here's a picture: http://imageshack.com/a/img835/504/m0fc.png
UPDATE:
Problem fixed!
Now i create a new String URL in the draw() method of MultipleTracksDrawer class and i give it to the AsyncTask (as input parameter). In this way it works. I edited the code.
Related
In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.
I am writing a program, in which i have to show calculated distance between two locations, from current location to destination location, and to get that i have written a method which calculates total distance between locations, now the main point is i am not getting distance value in TextView.
and here is my code, please check below:
LocationsActivity.java:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(LocationsActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("locations");
Log.d("jarray", jarray.toString());
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
locations = new Locations();
locations.setName(object.getString("name"));
locations.setLatitude(object.getString("latitude"));
locations.setLongitude(object.getString("longitude"));
actorsList.add(locations);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
public void distanceBetweenTwoLocations() {
Location currentLocation = new Location("");
currentLocation.setLatitude(latitude);
currentLocation.setLongitude(longitude);
for (int i = 0; i < actorsList.size(); i++) {
Location destinationLocation = new Location(" ");
destinationLocation.setLatitude(Double.valueOf(actorsList.get(i).getLatitude()));
destinationLocation.setLongitude(Double.valueOf(actorsList.get(i).getLongitude()));
double inMeters = currentLocation.distanceTo(destinationLocation);
double totalDistance = inMeters / 1000;
locations.setDistance(totalDistance + "");
}
}
}
}
Problem is with your distanceBetweenTwoLocations() method.
you are adding location data in actorsList at doInBackground method while you are retrieving data from locationsList
Still same mistake with your getView method. you are adding data in Locations list while in getView you are fetching data from locationsList
Updated :
you are passing actorsList to the adapter while you are assigning distance to the locations list.
Check with Following Code :
you need to call the following method at onPostExecute before notifying adapter adapter.notifyDataSetChanged();
public void distanceBetweenTwoLocations() {
Location currentLocation = new Location("");
currentLocation.setLatitude(latitude);
currentLocation.setLongitude(longitude);
for (int i = 0; i < actorsList.size(); i++) {
Locations mLocations = (Locations) actorList.get(i);
Location destinationLocation = new Location(" ");
destinationLocation.setLatitude(Double.valueOf(actorsList.get(i).getLatitude()));
destinationLocation.setLongitude(Double.valueOf(actorsList.get(i).getLongitude()));
double inMeters = currentLocation.distanceTo(destinationLocation);
double totalDistance = inMeters / 1000;
mLocations.setDistance(totalDistance + "");
}
}
}
I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#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(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}
I have the following class GetPlaces already, which will take the Google Places API URL new GetPlaces().execute("https://maps.googleapis.com/maps/api/place/search/json?types=cafe&rankby=distance&location=33.897835,-117.955759&sensor=false&key=MyKey"); that gets called in my main activity onCreate() and Parses the output.
private class GetPlaces extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : urls) {
//execute search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient.execute(placesGet);
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(placesContent);
BufferedReader placesReader = new BufferedReader(placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
protected void onPostExecute(String data) {
// TODO: check this.exception
// TODO: do something with the feed
/*
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
*/
super.onPostExecute(data);
// Dismiss the progress dialog
if(data !=null)
{
JSONObject jsonObj;
try {
jsonObj = new JSONObject(data);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String name = result.getString("name");
/*
String icon = result.getString("icon");
String address = result.getString("vicinity");
String rating = result.getString("rating");
String price = result.getString("price_level");
String webiste = result.getString("website");
//String review = result.getString("reviews");
*/
Log.d("tag", "name: " + name);
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.out.println(dat);
}
}
I have a few questions about this code:
I get an org.json.JSONException: No value for reviews error and I'm not sure what the best way to check for that is.
How can get Images of the place? I don't mean icon but how can I get the photos in the photos[] array?
How can I retrieve this data in my Main Activity's onCreate method or a helper function?
Try This:-
This url will help you to find/search NearByPlaces.....
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + ","
+ mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=--Your--Key--");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
Try to pass url as below.You have to put radius also in url for finding place(in your example cafe).& after getting places you can use Marker option for marking places.for that you can use your images as marker
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=2000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=Your+Key");
GetPlaces placesTask = new GetPlaces();
placesTask.execute(sb.toString());
I'm trying to get Latitude, Longitude and Name from a SQL Query on Java.
The problem is, when i call the Ubic() function, i get this error:
http://i.imgur.com/QD7JZjRh.jpg
http://i.imgur.com/xvzJ9ckh.jpg
This is the code that i added an the error is caused by String Latlon[][] = com.Ubic();
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
double latitud;
double longitud;
String nombre;
Datos com = new Datos();
String latlon[][] = com.Ubic(); //HERE IS THE PROBLEM!
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(posicion).title(nombre));
}
}
The file Datos.java is what i called from the Main Thread.
public class Datos {
public String[][] Ubic() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://MY.IP/FOLDER/QUERY.php");
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
JSONArray arr = object.getJSONArray("products");
String[] lat = new String[arr.length()+1];
String[] lon = new String[arr.length()+1];
String[] nombre = new String[arr.length() + 1];
String[][] latlon = new String[arr.length() + 1][5];
for (int i = 0; i < arr.length(); i++) {
lat[i] = arr.getJSONObject(i).getString("latitude");
lon[i] = arr.getJSONObject(i).getString("longitude");
name[i] = arr.getJSONObject(i).getString("name");
latlon[i][0] = lat[i];
latlon[i][6] = lon[i];
latlon[i][2] = name[i];
}
return latlon;
} catch (JSONException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
private static String parse(String string) {
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
}
return answer;
}}
How can i solve this?
NetworkOnMainThreadException: This exception is thrown when an application attempts to perform a networking operation (HTTP request in your case) on its main thread.
You should call com.Ubic(); method on asynctask then only above code will work.
Refer here http://android-developers.blogspot.in/2009/05/painless-threading.html
You will find better soltion here
AsyncTask Android example
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html