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());
Related
I am trying to get all the species result from the first url but sadly, my for loop can only retrieve one species from my first url and I don't know what's the correct logic here. Hope you can help me. I know the problem is my for loop but I don't know how to construct it correctly. Sorry. Newbie here.
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?species_name="
+ search_species;
pDialog.setMessage("Loading data...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("tem");
for(int i = 0; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
species_id = o.getString("localname");
common = o.getString("name");
scientific = o.getString("scientificname");
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?speciesid=" + species_id;
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("locationid", c.getString("locationid"));
map.put("brgy", c.getString("brgy"));
map.put("town", c.getString("town"));
map.put("latitude", c.getString("latitude"));
map.put("longitude", c.getString("longitude"));
map.put("speciesid", local);
map.put("flowercolor", c.getString("flowercolor"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
This is my getHttpGet:
public static String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
and this is the PHP file:
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$species_name = $_GET['species_name'];
$sql = "SELECT * from tbl_species WHERE CONCAT_WS(name, localname,
scientificname, familyname, flowercolor, leafshape) LIKE '%$species_name%'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
$arr['aaData'] = array();
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode(array('tem' => $tem));
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
Specifically, my for loop can only get the first species, after getting that, the for loop stops to get the others. I don't know what's wrong and what I should change. I'm creating a project that can search a species by name, by color, by shape etc.
Just a guess but maybe because you use the same int in both for loops
for(int i = 0; i<array.length(); i++)
for(i = 0; i < data.length(); i++){
You have a NetworkOnMainThreadException and your app crashes when you handle the second url.
You could have told us of the crash.
You should execute all network/internet code in a thread or asynctask.
You must have 2 variables to save the values in PHP file.and use array_push for save all values in an array
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?type=first&species_name="
+ search_species;
.
.
.
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?type=tow&speciesid=" + species_id;
try {.....
and in PHP file
$type = $_GET['type'];
$response1 = array();
$response2 = array();
.
.
.
while($row[] = $result->fetch_assoc()) {
if (type ==="fist"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}elseif (type ==="tow"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}
}////end while
if (type ==="fist"){
echo $response1;
}elseif(type1 ==="tow"){
echo $response2;
}
.
.
.
I can retrieve data through JSON in listview but I want to show data relative to the user logged in so for that I have to Post username to PHP script. I don't have any idea how to post the username to PHP script and then get respond from web server.
private class GetFixture extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_ITEMS);
String json = serviceClient.makeServiceCall(URL_ITEMS,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps","> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
String teamA = c.getString(TAG_TEAMA);
Log.d("teamA", teamA);
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixture.put(TAG_TEAMA, teamA);
matchFixture.put(TAG_TEAMB, teamB);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
Doctor_Names.this, matchFixtureList,
R.layout.list_item, new String[] {
TAG_MATCHID, TAG_TEAMA,TAG_TEAMB
}
, new int[] {
R.id.teamA,R.id.name,
R.id.teamB
}
);
setListAdapter(adapter);
}
sir this code perfectly show me all data from this server but i want some specific data like i want to show data related to the person who is logged in so for that i have to pass the user name to PHP script so dont have idea to POST any thing to web on the basis of which i can filter data
Here is an example:
JSONObject obj = new JSONObject();
obj.put("username", "YourUser");
HttpUrlConnectionJson.sendHTTPData("http://" + serverAddress + "/api/SomeUserMethod", obj);
HttpUrlConnectionJson class
public class HttpUrlConnectionJson {
private static final String TAG = "HttpUrlConnectionJson";
public static String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d(TAG, stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e(TAG, connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e(TAG, exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
I hope this help
I am trying to click a hyperlink and call method in android programming...
But the problem is , the link is not showing up and neither the method is getting called. How to achieve this result?
I am basically a javascript/jsp developer, this is my first android application , which i am learning. Accordingly i am trying to click link and call method with parameter....
Results looking like
Java code
private class CallAPI extends AsyncTask<String, String, String> {
private String Content;
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
emailVerificationResult result = null;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
System.out.println("test");
BufferedReader reader = null;
// Get the server response
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
/****************** Start Parse Response JSON Data *************/
String OutputData = "<center><b><u>Weight Training</u></b></center><br/><br/>";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("articleList");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for (int i = 0; i < lengthJsonArr; i++) {
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("menu_name").toString();
String number = jsonChildNode.optString("id").toString();
String date_added = jsonChildNode.optString("parent_id").toString();
OutputData += " " +
String.format("<a onClick='verifyEmail("+number+","+date_added+")'><b>"+name+"<b> "+ number+" "+ date_added+"</a> ") +"<br/><br/>";
}
/****************** End Parse Response JSON Data *************/
/* Show Parsed Output on screen (activity) */
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resultToDisplay =OutputData ;
return resultToDisplay;
}
// This is the method that is called when the submit button is clicked
public void verifyEmail(String m,String p) {
String urlString = apiURL + "mid=" + m + "&pid=" + p;
new CallAPI().execute(urlString);
}
protected void onPostExecute(String result) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
Update:
Instead of link, can i put a button and provide on click method and pass parameter to the method
(Thankfully) You cannot call a function using HTML tags in android. Instead try setting ClickableSpan on you you TextView to get the desired effect
SpannableString ss = new SpannableString("Click Me to do magic");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
doSomeMagic();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
}
};
// apply the clickable span on "Click Me" part which is on index 0 -> 7
// 8 is used because it goes from a -> b-1
ss.setSpan(clickableSpan, 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView = (TextView) findViewById(R.id.foo);
textView.setText(ss);
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);
}
}
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.