I need to extract values from the api of a city to a class in my own project.
This is the class i want to convert to.
public class Parada {
#SerializedName("wgs84_pos:long")
private long lon;
#SerializedName("wgs84_pos:lat")
private long lat;
#SerializedName("ayto:parada")
private String parada;
#SerializedName("vivo:address1")
private String direccion;
}
public class Santander {
private List<Result> results;
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
This is my code.
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://datos.santander.es/api/datos/paradas_bus.json");
httpGet.setHeader("content-type", "application/json");
HttpResponse resp = httpClient.execute(httpGet);
String respStr = EntityUtils.toString(resp.getEntity());
Gson gson = new GsonBuilder().create();
Santander santander = gson.fromJson(respStr, Santander.class);
List<Parada> paradas=new ArrayList<Parada>();
for (Parada p : santander.getResults())
{
paradas.add(p);
}
return paradas;
}
catch(Exception ex)
{
Log.e("ServicioRest", "Error!", ex);
}
Toast.makeText(getApplicationContext(), "Error grabbing values, return is null", Toast.LENGTH_LONG).show();
return null;
}
protected void onPostExecute(List<Parada> lParadas) {
if (lParadas!=null&&lParadas.size()>0) {
paradas=new Parada[lParadas.size()];
for (int i = 0; i < paradas.length; ++i){
paradas[i]=lParadas.get(i);
}
}
}
I need to get coordinates, address and name from the api into the array to then add them as points in a map, which is in a separate activity.
It gets the data in respStr but it doesnt go into class Santander
I dont think this is important but i add the code i use for the map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Parada[] paradas=MainActivity.paradas;
if (paradas!=null&¶das.length>0) {
List<MarkerOptions> marcadores=new ArrayList<MarkerOptions>();
for (int i = 0; i < paradas.length; ++i) {
Parada p=paradas[i];
LatLng pCoords = new LatLng(p.getLat(), p.getLon());
marcadores.add(new MarkerOptions().position(pCoords).title(p.getParada()));
}
}
// Add a marker in Sydney and move the camera
LatLng ayto = new LatLng(43.461, -3.80793);
mMap.moveCamera(CameraUpdateFactory.newLatLng(ayto));
}
Related
I have develop an application which draws the route between start point and the destination and also user will be able to mark some waypoints along that path and the route will be drawn correctly. But I can only get the distance when I only mark 2 places on the map. If I mark 2, 3 places it will not give me the distance. These are my codes,
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Error downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
URL I used to request
String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
Error I found when I used 4 points with 2 way points
This is in onPostExecute method on lines,
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
What I have done wrong here?
You Should have to try this by using retrofit.
Put this code on button click in MainActivity:-
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, OnMapReadyCallback {
private static final String LOG_TAG = "TAG1";
private static final String KEY = "Enter Your Key";
String displayResponseSource = "";
String displayResponseDestination = "";
private Button btn_search;
private GoogleMap map;
private APIInterface apiInterface;
private SupportMapFragment mapFragment;
private AutoCompleteTextView autoCompViewSource;
private AutoCompleteTextView autoCompViewDestination;
private String autocompletetextSource = "";
private String autocompletetextDestination = "";
private LatLng maplocationdestination;
private LatLng maplocationsource;
private double longitudeSource;
private double latitudeSource;
private double latitudeDestination;
private double longitudeDestination;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompViewSource = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewSource);
autoCompViewDestination = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewDestination);
btn_search = (Button) findViewById(R.id.btn_search);
autoCompViewSource.setAdapter(new GooglePlacesAutocompleteAdapterSource(this, R.layout.lv_item));
autoCompViewSource.setOnItemClickListener(this);
autoCompViewDestination.setAdapter(new GooglePlacesAutocompleteAdapterDestination(this, R.layout.lv_item));
autoCompViewDestination.setOnItemClickListener(this);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autocompletetextSource = autoCompViewSource.getText().toString();
autocompletetextDestination = autoCompViewDestination.getText().toString();
apiInterface = APIClient.getClient().create(APIInterface.class);
Call<ModelLatLong> call = apiInterface.getResponse(autocompletetextSource, KEY);
// autocompletetext,KEY
call.enqueue(new Callback<ModelLatLong>() {
#Override
public void onResponse(Call<ModelLatLong> call, Response<ModelLatLong> response) {
Log.i("TAG", response.code() + "");
ModelLatLong resource = response.body();
ArrayList<Results> resultsList = resource.getResults();
for (Results results : resultsList) {
longitudeSource = results.getGeometry().getLocation().getLng();
latitudeSource = results.getGeometry().getLocation().getLat();
Log.i("TAG1", displayResponseSource + "HI");
}
displayResponseSource = latitudeSource+ "," + longitudeSource;
// Toast.makeText(MainActivity.this, displayResponseSource, Toast.LENGTH_SHORT).show();
maplocationsource = new LatLng(latitudeSource, longitudeSource);
map.addMarker(new MarkerOptions()
.position(maplocationsource)
.snippet(autocompletetextSource)).showInfoWindow();
CameraUpdate center = CameraUpdateFactory.newLatLngZoom(maplocationsource, 14);
map.animateCamera(center);
}
#Override
public void onFailure(Call<ModelLatLong> call, Throwable t) {
Log.i("TAG1", "Failed");
call.cancel();
}
});
Call<ModelLatLong> calldes = apiInterface.getResponse(autocompletetextDestination, KEY);
// autocompletetext,KEY
calldes.enqueue(new Callback<ModelLatLong>() {
#Override
public void onResponse(Call<ModelLatLong> call, Response<ModelLatLong> response) {
Log.i("TAG", response.code() + "");
ModelLatLong resourcedes = response.body();
ArrayList<Results> resultsListdes = resourcedes.getResults();
for (Results results : resultsListdes) {
longitudeDestination = results.getGeometry().getLocation().getLng();
latitudeDestination = results.getGeometry().getLocation().getLat();
Log.i("TAG1", displayResponseDestination + "HI");
}
displayResponseDestination = latitudeDestination + "," + longitudeDestination;
// Toast.makeText(MainActivity.this, displayResponseDestination, Toast.LENGTH_SHORT).show();
maplocationdestination = new LatLng(latitudeDestination, longitudeDestination);
map.addMarker(new MarkerOptions()
.position(maplocationdestination)
.snippet(autocompletetextSource)).showInfoWindow();
CameraUpdate center = CameraUpdateFactory.newLatLngZoom(maplocationdestination, 14);
map.animateCamera(center);
}
#Override
public void onFailure(Call<ModelLatLong> call, Throwable t) {
Log.i("TAG1", "Failed");
call.cancel();
}
});
Call<ModelRoutes> calldistance = apiInterface.getResponseDistance(Get Your Source Latitude and Longitude Here(Eg. 20.9127766,73.7531254), Get Your Destination Latitude and Longitude Here in String(Eg. 23.0098149, 72.5035273), KEY);
calldistance.enqueue(new Callback<ModelRoutes>() {
#Override
public void onResponse(Call<ModelRoutes> call, Response<ModelRoutes> response) {
String displayResponse = "";
ModelRoutes resourcedis = response.body();
Log.i("TAG", response.code() + "Hello");
ArrayList<Routes> routesList = resourcedis.getRoutes();
for (Routes routes : routesList) {
ArrayList<Legs> legsList = routes.getLegs();
for (Legs legs : legsList) {
String killoMeter = legs.getDistance().getText();
double timeDistance = legs.getDistance().getValue();
displayResponse += "\n Killometer : " + killoMeter + "\n Time Duration : " + timeDistance + "\n";
Log.i("TAG1", displayResponse + "HI");
}
}
Toast.makeText(MainActivity.this, displayResponse, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ModelRoutes> call, Throwable t) {
Log.i("TAG1", "Failed");
call.cancel();
}
});
}
});
}
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/autocomplete/json");
sb.append("?key=Enter Your Key Here");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapterSource extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapterSource(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Object getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
class GooglePlacesAutocompleteAdapterDestination extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapterDestination(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Object getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
ModelRoutes.java
public class ModelRoutes extends Legs {
ArrayList<Routes> routes = null;
public ArrayList<Routes> getRoutes() {
return routes;
}
public void setRoutes(ArrayList<Routes> routes) {
this.routes = routes;
}
}
Routes.java
public class Routes extends Legs{
ArrayList<Legs> legs = null;
public ArrayList<Legs> getLegs() {
return legs;
}
public void setLegs(ArrayList<Legs> legs) {
this.legs = legs;
}
}
Legs.java
public class Legs {
Distances distance;
Durations duration;
public Distances getDistance() {
return distance;
}
public void setDistance(Distances distance) {
this.distance = distance;
}
public Durations getDuration() {
return duration;
}
public void setDuration(Durations duration) {
this.duration = duration;
}
public class Distances{
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
String text;
double value;
}
public class Durations{
String text;
double value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
}
APIClient.java
public class APIClient {
private static Retrofit retrofit = null;
static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
APIInterface.java
public interface APIInterface {
#GET("/maps/api/geocode/json")
Call<ModelLatLong> getResponse(
#Query("address") String str,
#Query("key") String str2);
#GET("/maps/api/directions/json")
Call<ModelRoutes> getResponseDistance(
#Query("origin") String str,
#Query("destination") String str1,
#Query("key") String str2);
}
ModelLatLong.java
public class ModelLatLong extends Results {
private ArrayList<Results> results=null;
public ArrayList<Results> getResults() {
return results;
}
public void setResults(ArrayList<Results> results) {
this.results = results;
}
}
Results.java
public class Results extends Geometry{
private Geometry geometry;
public Geometry getGeometry() {
return this.geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
}
Geometry.java
public class Geometry extends Location{
private Location location;
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
}
Location.java
public class Location {
private double lat;
private double lng;
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gmapplaceapi.MainActivity">
<AutoCompleteTextView
android:id="#+id/autoCompleteTextViewSource"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Please enter Source place"
>
<requestFocus />
</AutoCompleteTextView>
<AutoCompleteTextView
android:id="#+id/autoCompleteTextViewDestination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="#+id/autoCompleteTextViewSource"
android:hint="Please enter Destination place"
>
<requestFocus />
</AutoCompleteTextView>
<Button
android:id="#+id/btn_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"
android:layout_below="#+id/autoCompleteTextViewDestination"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/btn_search"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
</RelativeLayout>
lv_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:textSize="20dp" />
Don't forget to put Internet Permission in manifest file.
I have spent days on this, but I can't find a solution to my problem:
I'm developing an app that retrieves a list of theaters showing some movie selected by the user, parsing an HTML page in an AsyncTask.
I want to visualize those theaters on a Map with markers, so I need coordinates: once the "GetCinemaList" AsyncTask is completed, I try to populate my markerList in onPostExecute.
I have an SQLite db in which I store [theater|city|lat|lng]. So I first look up in the db, if it is not found I want call another AsyncTask to retrieve coordinates from HTTP google geocoding ('cause device geocoder returns null, causing the app to crash)
The problem is I am not able to return the LatLng point to the first AsyncTask...
I have tried to use listeners and to override processFinish(LatLng p), but I can't assign the value to my variable cause, accessing it from inner class it should be final.
Any help/idea? Thanks!
Here my code (containing error) for the AsyncTasks , in my Activity.
private class GetCinemaList extends AsyncTask<URL, Void, List<String>> {
private Context mContext;
public GetCinemaList(Context c){
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
List<String> cinemas = new ArrayList<>();
Document docHTML = null;
try {
docHTML = QueryUtils.makeRequest(urls[0]);
cinemas = QueryUtils.extractCinemasFromHTML(mTitile, docHTML);
} catch (IOException e) {
Log.e("JSwa", "Problem making request for parsing HTML "+e);
}
return cinemas;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
cinemaList = result;
LatLng point;
pointList = new ArrayList<>();
for (String elem : cinemaList) {
String name = elem.split("\t")[0];
String orari = elem.split("\t")[1];
Cursor cursor = queryDB(mCinemaDbR, city, name);
if (!cursor.moveToFirst()) {
// call geocoding service
new LatLongFromService(name.concat(" " + city), new AsyncResponse() {
#Override
public void processFinish(LatLng output) {
point = output;
}
}).execute();
Log.d("JSwa", "Inserting point "+point.toString());
// insert new value in the database
long id = addCimena(mCinemaDbW, name, city, String.valueOf(point.latitude), String.valueOf(point.longitude));
// insert new value in the list
MarkerOptions marker = new MarkerOptions().position(point).title(name).snippet(orari);
pointList.add(marker);
}
else{
double lat = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LAT)));
double lng = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LNG)));
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat,lng)).title(name)
.snippet(orari);
pointList.add(marker);
}
cursor.close();
}
for (MarkerOptions marker : pointList){
m_map.addMarker(marker);
}
}
}
// Sometimes happens that device gives location = null
public class LatLongFromService extends AsyncTask<Void, Void, StringBuilder> {
String place;
public AsyncResponse delegate = null;
public LatLongFromService(String place, AsyncResponse resp) {
this.place = place;
delegate = resp;
}
#Override
protected StringBuilder doInBackground(Void... params) {
try {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + this.place + "&sensor=false";
URL url = new URL(googleMapUrl);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(
conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
return jsonResults;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
try {
JSONObject jsonObj = new JSONObject(result.toString());
JSONArray resultJsonArray = jsonObj.getJSONArray("results");
JSONObject location = resultJsonArray
.getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
String lat_helper = location.getString("lat");
double lat = Double.valueOf(lat_helper);
String lng_helper = location.getString("lng");
double lng = Double.valueOf(lng_helper);
delegate.processFinish(new LatLng(lat, lng));
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
How to add TAG to every marker and set the UniqueId on every marker.
Uniqueid's of every marker received from the server
Here is DoInBackgroung Code please help me
for (int i = 0; i < jsonarray.length(); i++) {
// ModelClass s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), ModelClass.class);
ModelClass modelClass = new Gson().fromJson(jsonarray.getJSONObject(i).toString(), ModelClass.class);
LatLng latLng = new LatLng(Double.parseDouble(modelClass.getLatitude()), Double.parseDouble(modelClass.getLongitude())); // Use your server's methods
latLngList.add(latLng);
Here is code to add marker
private void AddPointer() {
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}
OnpostExecute code where i add the Marker that received from the server in this time i have two markers on server with its uniqueId's
protected void onPostExecute(Boolean result) {
// dialog.cancel();
// adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
AddPointer();
}
Here is Model Class
public class ModelClass {
#SerializedName("longi")
public String longitudeServer;
#SerializedName("lati")
public String latitudeServer;
#SerializedName("uniqueid")
public String uniqueidSserver;
public ModelClass(){
}
public String getLongitude(){
return longitudeServer;
}
public String getLatitude(){
return latitudeServer;
}
public String getUniqueId(){
return uniqueidSserver;
}
}
Try this you can set diffrent marker and give uniqueid or name
// Prepare Model Class like this way
public class LocationDetail
{
public String longitudeServer;
public String latitudeServer;
public String uniqueidSserver;
public String getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(String longitudeServer) {
this.longitudeServer = longitudeServer;
}
public String getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(String latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
//Prepare the arraylist like this
try
{
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject
.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject
.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString(
"UniqueId").toString());
list.add(modelclass);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
//Now pass above Arraylist to method
private void showMap(ArrayList<Reach_Us> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitude();
longitude = list.get(i).getLongitude();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude())).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Pravin i do like this.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
try {
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
// JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonarray.length(); i++) {
jsonObject = jsonarray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString("UniqueId").toString());
list.add(modelclass);
}
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
and also
private void showMap(ArrayList<LocationDetail> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
mMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
mMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
mMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
mMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitudeServer();
longitude = list.get(i).getLongitudeServer();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitudeServer(), list
.get(i).getLongitudeServer()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And also in
public class LocationDetail
{
public double longitudeServer;
public double latitudeServer;
public String uniqueidSserver;
public double getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(double longitudeServer) {
this.longitudeServer = longitudeServer;
}
public double getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(double latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
But error in this line
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build(); it shows LatLnd Double Double cannot be applied to Double
How i Receive this data into to Model class i want to make a model class like getter setter andi use data from getter setter.
I want to make Model class
Basically i store it into variables not in separate class so i want to make model class
> Here is my code
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/* dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);*/
Toast.makeText(getApplicationContext(), "fetch data from server", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
LatLng latLng = new LatLng(Double.parseDouble(latitudeServer), Double.parseDouble(longitudeServer));
latLngList.add(latLng);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}
Although #Guillaume answer is correct, i would like to suggest a better and faster way. You can use a third party library LoganSquare to serialize and parse your models to and from JSON respectively. You just have to annotate your models and use LoganSquare class to parse data.
In your case it would be like this: (pay close attention to annotations above class name and fields)
#JsonObject
public class MyServer {
#JsonField(name = "longi")
public String longitudeServer;
#JsonField(name = "lati")
public String latitudeServer;
#JsonField(name = "uniqueid")
public String uniqueidSserver;
public MyServer(){
// blank constructor is required
}
}
Now use LoganSquare static class to parse the json response received from server:
for (int i = 0; i < jsonarray.length(); i++) {
MyServer s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), MyServer.class);
LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
latLngList.add(latLng);
}
First define your desired model into a class with for example a constructor allwing to create a new instance from a JSONObject
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
class MyServer {
private String longitudeServer;
private String latitudeServer;
private String uniqueidSserver;
public MyServer(JSONObject obj){
try{
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}catch(JSONException jse){
e.printStackTrace();
}
}
public String getLongitude(){
return longitudeServer;
}
public void setLongitude(String longitudeServer){
this.longitudeServer = longitudeServer;
}
//... More setter and getter here
}
// ... The existing code of your async task here
}
Once this done your can instanciate a new MyServer and use its getter/setter
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
MyServer s = new MyServer(obj); // Create your server from the JSONObject
LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
latLngList.add(latLng);
}
I am trying to implement an google map app that will store the google marker on the cloud database. But I have a problem to get back the coordinate of the marker on the cloud.
How do I return a List generated in an AsyncTask back to a custom java class? The problem that I have encountered right now is when I initialize a Alistener class in different class, for example, in class B:
AListener a = new Alistener( ..., ... );
...
a.getMarkerData();
List<Pair> myList = a.getList();
myList is just null, and I think because the a.getList() has executed before the data is fetched back from that cloud database in onPostExecute(). Any insight will help a lot.
This is my java class:
public class AListener {
protected static final String TAG = null;
double lat, lon;
List<Pair> myList = new ArrayList<Pair>();
CustomMarkerListener( double lat, double lon ) {
this.lat = lat;
this.lon = lon;
}
public void getMarkerData() {
MarkerDataInfo ms = new MarkerDataInfo();
ms.execute( UserLogin.ITEM_URI );
}
public void setList(List<Pair> myList ) {
this.myList = myList;
}
public List<Pair> getList() {
return this.myList;
}
}
And this is my AsyncTask an inner class of AListener:
private class MarkerDataInfo extends AsyncTask<String, Void, List<Pair>> {
List<Pair> list;
private CustomMarkerListener mLis;
public MarkerDataInfo() {}
public MarkerDataInfo( CustomMarkerListener mLis ) {
this.mLis = mLis;
}
#Override
protected List<Pair> doInBackground(String... url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet( UserLogin.ITEM_URI);
list = new ArrayList<Pair>();
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Log.d(TAG, data);
JSONObject myjson;
try {
myjson = new JSONObject(data);
JSONArray array = myjson.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String markerOfUser = obj.get("marker").toString();
if( markerOfUser.equals( UserLogin.accountName )) {
String latname = obj.get("lat").toString();
String lonname = obj.get("lon").toString();
double latData = Double.parseDouble(latname);
double lonData = Double.parseDouble(lonname);
list.add( new Pair( latData, lonData ));
}
}
} catch (JSONException e) {
Log.d(TAG, "Error in parsing JSON");
}
} catch (ClientProtocolException e) {
Log.d(TAG, "ClientProtocolException while trying to connect to GAE");
} catch (IOException e) {
Log.d(TAG, "IOException while trying to connect to GAE");
}
return list;
}
protected void onPostExecute(List<Pair> list) {
super.onPostExecute(list);
mLis.setList( list );
Log.d("CUstome", "" + list.size());
}
}
If only one request is active at any time, you can use singleton pattern for your class.