This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
in my applicationi want to show my locations from database and i find code do that but i get this error so please help me !!
'here is my MainnActivity '
package com.ry.rhcomptence.accessiblemaroc;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
public class MainnActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainn);
// Getting reference to SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Creating GoogleMap from SupportMapFragment
//mGoogleMap = fragment.getMap();
fragment.getMapAsync(this);
// Setting OnClickEvent listener for the GoogleMap
/**mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
addMarker(latlng);
sendToServer(latlng);
}
});*/
// Starting locations retrieve task
new RetrieveTask().execute();
}
// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(latlng.latitude + "," + latlng.longitude);
mGoogleMap.addMarker(markerOptions);
}
// Invoking background thread to store the touched location in Remove MySQL server
private void sendToServer(LatLng latlng) {
new SaveTask().execute(latlng);
}
#Override
public void onMapReady(GoogleMap googleMap) {
// Enabling MyLocation button for the Google Map
/**if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mGoogleMap.setMyLocationEnabled(true);*/
}
// Background thread to save the location in remove MySQL server
private class SaveTask extends AsyncTask<LatLng, Void, Void> {
#Override
protected Void doInBackground(LatLng... params) {
String lat = Double.toString(params[0].latitude);
String lng = Double.toString(params[0].longitude);
String strUrl = "https://accessiblemaroc.000webhostapp.com/save.php";
URL url = null;
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
connection.getOutputStream());
outputStreamWriter.write("lat=" + lat + "&lng="+lng);
outputStreamWriter.flush();
outputStreamWriter.close();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String strUrl = "https://accessiblemaroc.000webhostapp.com/retrieve.php";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
addMarker(latlng);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
'here where is the problem MarkerJSONParser.JAVA :'
package com.ry.rhcomptence.accessiblemaroc;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MarkerJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jMarkers =null;
try {
/** Retrieves all the elements in the 'markers' array */
jMarkers = jObject.getJSONArray("markers");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getMarkers with the array of json object
* where each json object represent a marker
*/
return getMarkers(jMarkers);
}
private List<HashMap<String, String>> getMarkers(JSONArray jMarkers){
int markersCount = jMarkers.length();
List<HashMap<String, String>> markersList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> marker = null;
/** Taking each marker, parses and adds to list object */
for(int i=0; i<markersCount;i++){
try {
/** Call getMarker with marker JSON object to parse the marker */
marker = getMarker((JSONObject)jMarkers.get(i));
markersList.add(marker);
}catch (JSONException e){
e.printStackTrace();
}
}
return markersList;
}
/** Parsing the Marker JSON object */
private HashMap<String, String> getMarker(JSONObject jMarker){
HashMap<String, String> marker = new HashMap<String, String>();
String lat = "-NA-";
String lng ="-NA-";
try {
// Extracting latitude, if available
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Extracting longitude, if available
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
marker.put("lat", lat);
marker.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
}
'and finally this is the ERROR'
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.ry.rhcomptence.accessiblemaroc.MarkerJSONParser.parse(MarkerJSONParser.java:19)
at com.ry.rhcomptence.accessiblemaroc.MainnActivity$ParserTask.doInBackground(MainnActivity.java:191)
at com.ry.rhcomptence.accessiblemaroc.MainnActivity$ParserTask.doInBackground(MainnActivity.java:181)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
You are not trying to get data in your ParserTask
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
addMarker(latlng);
}
}
}
You mentioned that this is a:
//Background thread to parse the JSON data retrieved from MySQL server
But you are not retrieving data from your MySQL Server which in return would give you nothing. And when you pass that nothing to your MarkerJSONParser and try to parse nothing. It would result to the NullPointerException.
Related
how to start activity when click on marker with json and clustering
my map is already clustering but i cant start to new activity when click on marker without title
this is my code
package tmg.tower;
/**
* Created by DIMAS on 25/06/2015.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.ClusterManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity implements GoogleMap.OnMarkerClickListener, View.OnClickListener {
private JSONParser json;
private LatLng myLocation;
ArrayList<HashMap<String, String>> dataMap = new ArrayList<HashMap<String, String>>();
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
Server serv = new Server();
String conn = serv.connection();
String url = conn + "********";
JSONArray str_json = null;
static final int showerror = 1;
public static final String SP = "shareAt";
SharedPreferences shareAt;
public static final String KEY_LAT_TUJUAN = "lat_tujuan";
public static final String KEY_LNG_TUJUAN = "lng_tujuan";
static final LatLng AWAL = new LatLng(3.584695, 98.675079);
Button mBtnFind;
EditText etPlace;
Button searchlist;
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LatLng myPosition;
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS Disabled, Buka Setting dan Aktifkan GPS?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_LONG).show();
}
if (cek_status(this)) {
Server serv = new Server();
conn = serv.connection();
new getListInfo().execute();
} else {
showDialog(showerror);
}
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment) myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
myMap.setOnMarkerClickListener(this);
myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AWAL, 15));
myMap.setBuildingsEnabled(true);
myMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
mBtnFind = (Button) findViewById(R.id.btn_show);
etPlace = (EditText) findViewById(R.id.et_place);
searchlist = (Button) findViewById(R.id.searchlist);
searchlist.setOnClickListener(this);
mBtnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting the place entered
String location = etPlace.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://**********";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String siteid = "Site_ID=" + location;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + siteid + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
});
}
public void onClick (View v){
Intent i = new Intent(MainActivity.this,Search.class);
startActivity(i);
}
public boolean cek_status(Context cek) {
ConnectivityManager cm = (ConnectivityManager) cek.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case showerror:
AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
errorDialog.setTitle("Error Connection");
errorDialog.setMessage("Please check your internet connection");
errorDialog.setNeutralButton("exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.this.finish();
startActivity(exit);
}
});
AlertDialog errorAlert = errorDialog.create();
return errorAlert;
default:
break;
}
return dialog;
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#SuppressLint("LongLogTag")
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("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
class getListInfo extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Loading server...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json = jParser.AmbilJson(url);
try {
str_json = json.getJSONArray("tower");
for (int i = 0; i < str_json.length(); i++) {
JSONObject ar = str_json.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Site ID", ar.getString("Site ID"));
map.put("Site Name", ar.getString("Site Name"));
map.put("Address", ar.getString("Address"));
map.put("Lattitude", ar.getString("Lattitude"));
map.put("Longitude", ar.getString("Longitude"));
dataMap.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
mClusterManager = new ClusterManager<MyItem>(getApplicationContext(), myMap);
myMap.setOnCameraChangeListener(mClusterManager);
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
for (int i = 0; i < dataMap.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
List<MyItem> items = new ArrayList<MyItem>();
map = dataMap.get(i);
mClusterManager.addItem(new MyItem(Double.parseDouble(map.get("Lattitude")), Double.parseDouble(map.get("Longitude"))));
}
}
});
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);
}catch(Exception e){
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("Lattitude"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("Longitude"));
// Getting name
String name = hmPlace.get("Site ID");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Locate the first location
if(i==0)
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
#Override
public boolean onMarkerClick(Marker marker) {
myLocation = new LatLng(myMap.getMyLocation().getLatitude(), myMap.getMyLocation().getLongitude());
if (myLocation != null) {
Bundle bundle = new Bundle();
bundle.putDouble(KEY_LAT_TUJUAN, marker.getPosition().latitude);
bundle.putDouble(KEY_LNG_TUJUAN, marker.getPosition().longitude);
shareAt = getBaseContext().getSharedPreferences(SP, 0);
SharedPreferences.Editor editor = shareAt.edit();
String replace_string_first = marker.getTitle().replace(" ", "_");
editor.putString("Site ID", replace_string_first);
editor.putString("Lattitude", replace_string_first);
editor.putString("Longitude", replace_string_first);
editor.commit();
Intent intent = new Intent(MainActivity.this, Main.class);
intent.putExtras(bundle);
intent.putExtra("Site ID", replace_string_first);
intent.putExtra("Lattitude", replace_string_first);
intent.putExtra("Longitude", replace_string_first);
startActivity(intent);
}
return false;
}
}
how to get intent json object without marker.getTitle ?
thanks for help
I know this seems like a duplicate, but it's not.
I'm following a tutorial on google maps and I just cannot get throught this fail (notice this is my very first time developing in Android).
In function onCreateOptionsMenu I get the error I describe in title.
Here's my MainActivity.java (onCreateOptionsMenu is on bottom):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity
{
GoogleMap map;
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
TextView distancia_tiempo = new TextView(this);
this.tvDistanceDuration = distancia_tiempo; //this.findViewById(R.id.tv_distance_time);
// Initializing
this.markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
this.map = fm.getMap();
// Enable MyLocation Button in the Map
this.map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
this.map.setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng point)
{
// Already two locations
if (MainActivity.this.markerPoints.size() > 1)
{
MainActivity.this.markerPoints.clear();
MainActivity.this.map.clear();
}
// Adding new item to the ArrayList
MainActivity.this.markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (MainActivity.this.markerPoints.size() == 1)
{
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MainActivity.this.markerPoints.size() == 2)
{
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
MainActivity.this.map.addMarker(options);
// Checks, whether start and end locations are captured
if (MainActivity.this.markerPoints.size() >= 2)
{
LatLng origin = MainActivity.this.markerPoints.get(0);
LatLng dest = MainActivity.this.markerPoints.get(1);
// Getting URL to the Google Directions API
String url = MainActivity.this.getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin, LatLng dest)
{
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/** A method to download json data from url */
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("Exception while 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 = MainActivity.this.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(MainActivity.this.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 = point.get("distance");
continue;
} else if (j == 1)
{ // Get duration from the list
duration = 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);
}
MainActivity.this.tvDistanceDuration.setText("Distance:" + distance + ", Duration:" + duration);
// Drawing polyline in the Google Map for the i-th route
MainActivity.this.map.addPolyline(lineOptions);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
this.getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here's activity_main.xml:
<MapFragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</MapFragment>
Any ideas??
Hi I'm having an issue trying to retrieve information from an async task.
What I'm trying to achieve is get the lng/lat from a postcode and then display them on a map. Getting the lng/lat works fine, its just I cant work out how to get that information from the onPostExecute back to the onCreate in an array.
I can perform a loop to add the map markers there.
Anyone know how I go about this?
Updated code
This is the working code that also updates the zoom to fit all entries in. Might help some people out
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import com.example.coreoffice.library.GeocodeJSONParser;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBounds.Builder;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity
{
Button mBtnFind;
static GoogleMap mMap;
EditText etPlace;
private static final String TAG = "MainActivity";
static ArrayList<Double> lat = new ArrayList<Double>();
static ArrayList<Double> lng = new ArrayList<Double>();
static Builder bounds = new LatLngBounds.Builder();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_maps);
Log.v(TAG + "onCreate", "onCreate call");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
String[] location =
{ "WA32ED", "M30oft", "W21AA" }; // address
String url;
for (int i = 0; i < location.length; i++)
{
DownloadTask downloadTask = new DownloadTask();
url = "";
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location[i] + "&sensor=false";
Log.v("URL", url);
downloadTask.execute(url);
}
}
public static void processMap()
{
for (int i = 0; i < lat.size(); i++)
{
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat.get(i), lng.get(i));
markerOptions.position(latLng);
markerOptions.title("title");
mMap.addMarker(markerOptions);
bounds.include(new LatLng(lat.get(i), lng.get(i)));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 100));
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try
{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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("Exception while downloading url", e.toString());
}
finally
{
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>
{
String data = null;
#Override
protected String doInBackground(String... url)
{
try
{
data = downloadUrl(url[0]);
}
catch (Exception e)
{
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result)
{
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>>
{
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData)
{
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try
{
jObject = new JSONObject(jsonData[0]);
places = parser.parse(jObject);
}
catch (Exception e)
{
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list)
{
for (int i = 0; i < list.size(); i++)
{
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
MapsActivity.this.lat.add(lat);
MapsActivity.this.lng.add(lng);
MapsActivity.processMap();
Log.v("lat", Double.toString(lat));
Log.v("lng", Double.toString(lng));
}
}
}
}
As your AsyncTasks are, by definition, asynchronous, you cannot guarantee that they will be done before onCreate() finishes. You merely need to call a method in onPostExecute() of ParserTask to handle the "loop" you describe after the tasks have completed.
Your ArrayLists lat and lng are accessible to the inner classes that are your AsyncTasks, so you just need to add a few lines to onPostExecute():
protected void onPostExecute(List<HashMap<String, String>> list)
{
for (int i = 0; i < list.size(); i++)
{
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
MapsActivity.this.lat.add(lat);
MapsActivity.this.lng.add(lng);
Log.v("lat", Double.toString(lat));
Log.v("lng", Double.toString(lng));
}
processData();
}
Then create a method in MapsActivity:
private void processData()
{
// Do your loop here.
}
You can define an interface as callback for your ParserTask class, and call it in onPostExecute method.
First declare an interface:
public interface OnParseFinishedListener {
public void onFinished(/* required params */);
}
Then add these methods to your ParserTask:
public void setOnParseFinishedListener(OnParseFinishedListener listener){
this.listener = listener;
}
and in your onPostExecute add this line:
if(listener != null) {
listener.onFinished(/* pass params here! */);
}
Use a global variable to hold your HashMap, and then pass it from your Activity into your AsyncTask.
you Should do the donwloading and parsing in a single asynctask.
I would propose using loader instead of asynctask (as you will have a problem once your asynctask returns and your activity has been recreated (eg due to turning the screen or any other configuration change)
In onPostExecute you just call a method in your activity. There you can access your map object /fragment (which you store in an instance variable in onCreate).
Again use an asyncloader which behaves very similar to asynctask but will save you a lot of grief down the line even if it's slightly more complex in the beginning.
Hi I found this code to Plot markers on a map in Android using data from a JSON web service and the Google Maps Android API v2
Can anyone help me how to proceed update instantly marker without refreshing view to track position on the map
package com.example.google.maps.demo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* #author saxman
*/
public class MainActivity extends FragmentActivity {
private static final String LOG_TAG = "taxitag";
private static final String SERVICE_URL = "http://192.168.1.3/taxi.php";
protected GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)
))
);
}
}
}
thanks
you can use this,her you will get solution for updating markers.
link
I am using this code to draw driving direction between two points. My map is loading well and the points are getting while parsing.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import com.esysolutions.dilosys.Map.DirectionsJSONParser;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
public class LocationDrivingMap extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationdrivingdirection);
markerPoints = new ArrayList<LatLng>();
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fm.getMap();
if (map != null) {
map.setMyLocationEnabled(true);
String url = getDirectionsUrl();
Log.d("............FULL URL...................", url);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
private String getDirectionsUrl() {
String parameters = "origin=13.687140112679154,100.535258688032630&destination=13.683660045847258,100.53900808095932&sensor=false&units=metric&mode=driving";
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
/** A method to download json data from url */
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("Exception while 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) {
Log.d(">>>>>>>Inside DownloadTask<<<<<<<<<", url[0]);
// 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);
Log.d("++++++++++++++++++++Route", "" + routes);
} 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;
// 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);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
Log.d("??????????????? Points", "" + points);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
Log.d("************************* LineOptions", ""
+ lineOptions);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
13.687140112679154, 100.535258688032630), 2.0f));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Log inside point gets this value, but path is not showing here.
[lat/lng: (13.68719,100.53523), lat/lng: (13.68723,100.53524), lat/lng: (13.68728,100.53526), lat/lng: (13.68728,100.53526), lat/lng: (13.68721,100.5355), lat/lng: (13.68715,100.53573), lat/lng: (13.68709,100.53591), lat/lng: (13.68699,100.53616), lat/lng: (13.68693,100.53629), lat/lng: (13.68689,100.53635), lat/lng: (13.68679,100.5365), lat/lng: (13.68666,100.53666), lat/lng: (13.68656,100.53679), lat/lng: (13.68643,100.53691), lat/lng: (13.68622,100.53707), lat/lng: (13.68554,100.5375), lat/lng: (13.68509,100.5378), lat/lng: (13.68478,100.53804), lat/lng: (13.68469,100.53812), lat/lng: (13.68461,100.53818), lat/lng: (13.68456,100.53823), lat/lng: (13.68449,100.53828), lat/lng: (13.68439,100.53837), lat/lng: (13.68406,100.53868), lat/lng: (13.68381,100.53894), lat/lng: (13.68371,100.53905)]
Here I got the Solution for this Question :
package com.esysolutions.dilosys.v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import com.esysolutions.dilosys.Map.DirectionsJSONParser;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class LocationDrivingMap extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
MarkerOptions op;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationdrivingdirection);
markerPoints = new ArrayList<LatLng>();
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fm.getMap();
LatLng point1 = new LatLng(13.687140112679154, 100.535258688032630);
LatLng point2 = new LatLng(14.683660045847258, 105.53900808095932);
markerPoints.add(point1);
markerPoints.add(point2);
if (map != null) {
map.setMyLocationEnabled(true);
for (int j = 0; j < 2; j++) {
op = new MarkerOptions();
op.position(markerPoints.get(j));
if (markerPoints.size() == 1) {
op.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (markerPoints.size() == 2) {
op.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
map.addMarker(op);
}
if (markerPoints.size() >= 2) {
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + ","
+ origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
/** A method to download json data from url */
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("Exception while 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();
// 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);
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);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}