I have a MapsActivity in my app which starts by clicking on a button in MainActivity and when activity started I will get markers coordinates by JSON and show them in MapsActivity, but this will happen only in first time and once I press back and go to MainActivity and press the button again MapsActivity starts but markers won't be displayed in that . I tried to finish or destroy activity but that didn't help.
any help will be much appreciated
this is my MapsActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
check_activity = 1;
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
ma_fin = this;
MainActivity.maps_adv = 1;
if (flag == 1) {
map_update();
maps_adv = 0;
}
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
checkLocationPermission();
setUpMapIfNeeded();
map_update();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your Location");
mMap.addMarker(options);
float zoomLevel = 13.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
final ArrayList myList;
if (checker==0) {
myList = (ArrayList<Object>) getIntent().getSerializableExtra("maps");
}
else
{
checker = 0;
myList = maps;
}
mMap = googleMap;
mMap.clear();
for (int i = 0; i < myList.size(); i++) {
LatLng sydney = new LatLng(((Double) (((ArrayList) myList.get(i))).get(2)).doubleValue(), ((Double) (((ArrayList) myList.get(i))).get(3)).doubleValue());
mMap.addMarker(new MarkerOptions().position(sydney).title((String) (((ArrayList) myList.get(i))).get(1)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String position = "0";
String title = marker.getTitle();
for (int i = 0; i < myList.size(); i++) {
if (title.equals(((ArrayList) myList.get(i)).get(1).toString())) {
position = ((ArrayList) myList.get(i)).get(0).toString();
titlename = ((ArrayList) myList.get(i)).get(1).toString();
address = ((ArrayList) myList.get(i)).get(4).toString();
}
}
foo = Integer.valueOf(position);
a = ((ArrayList) myList.get(foo)).get(0).toString();
backgroundTask = new BackgroundTask(textView);
backgroundTask.execute();
map_check = 1;
MainActivity.maps_adv = 0;
return true;
}
});
} catch (RuntimeException e) {
e.printStackTrace();
}
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
jsonobj = new JSONObject();
jsonobj.put("hotel_id_post", foo);
Log.i("EEE", a);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
nameValuePairs.add(new BasicNameValuePair("func", "2"));
nameValuePairs.add(new BasicNameValuePair("adv", MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date", MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", "1"));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServerhotel = str.getStringFromInputStream(inputStream);
Log.e("responseqqqqqqq", "response -----" + responseServerhotel);
HotelList.jsonroom = new JSONObject(responseServerhotel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
if (responseServerhotel.equals("{\"types\":null}"))
{
MainActivity.nothing = "no room to show";
Intent intent = new Intent(MapsActivity.this,Nothing.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(MapsActivity.this, RoomList.class);
startActivity(intent);
}
}
}
private class BackgroundTask1 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask1(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
//mMap.clear();
jsonadv = new JSONObject();
jsonadv_cont = new JSONObject();
jsonobj = new JSONObject();
jsonads = new JSONObject();
MainActivity.features = "";
features_count = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("func", "11"));
nameValuePairs.add(new BasicNameValuePair("adv",
MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" +
features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date",
MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", num));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.e("response", "response -----" + responseServer);
jsonmap = new JSONObject(responseServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (backgroundTask != null) {
backgroundTask.cancel(true);
}
if (backgroundTask1 != null) {
backgroundTask1.cancel(true);
}
if (backgroundTask2 != null) {
backgroundTask2.cancel(true);
}
finish();
}
private class BackgroundTask2 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask2(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MainActivity.url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray mapsarr = jsonmap.getJSONArray("maps");
for (int i = 0; i < mapsarr.length(); i++) {
ArrayList<Object> mapping = new ArrayList<>();
JSONObject c = mapsarr.getJSONObject(i);
String id = c.getString("hotel_id");
String name = c.getString("hotel_name");
Double x = c.getDouble("hotel_x");
Double y = c.getDouble("hotel_y");
String address = c.getString("hotel_address");
mapping.add(0, id);
mapping.add(1, name);
mapping.add(2, x);
mapping.add(3, y);
mapping.add(4, address);
maps.add(i, mapping);
}
Log.i("MAPTEST", mapsarr.toString());
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
onMapReady(mMap);
checker = 1;
}
}
public static class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
}
public void map_update() {
maps.clear();
backgroundTask1 = new BackgroundTask1(textView);
backgroundTask1.execute();
}
public static void refresh()
{
flag = 0;
MapsActivity ma = new MapsActivity();
ma.map_update();
}
Related
I will be posting all of my codes here and a sample output of my project. I have set the alternative to yes to display the alternate routes but problem is, how do I parse all the distance from all routes? It only gets the distance of the main route but not the alternate routes. How do I change my Parse java class to get all the directions in alternate routes and display it?
public class ThirdFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener,DirectionFinderListener,AdapterView.OnItemClickListener {
/**************************************************************/
// private GoogleMap mMap;
private ImageButton btnFindPath;
private AutoCompleteTextView etOrigin;
private AutoCompleteTextView etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
private static final String LOG_TAG = "Google Places Autocomplete";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "MY API KEY HERE";
//FOR COLLAPSING TOOLBAR
private CollapsingToolbarLayout collapsingToolbarLayout = null;
/**************************************************************************************************************/
double latitude;
double longitude;
GoogleMap mMap;
MapView mapView;
View Myview;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Myview = inflater.inflate(R.layout.activity_third_fragment, container, false);
mapView = (MapView) Myview.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
/********************************************************************/
collapsingToolbarLayout = (CollapsingToolbarLayout) Myview.findViewById(R.id.collapsing_toolbar);
/****************************************************************************************/
btnFindPath = (ImageButton) Myview.findViewById(R.id.btnFindPath);
etOrigin = (AutoCompleteTextView) Myview.findViewById(R.id.etOrigin);
etDestination = (AutoCompleteTextView) Myview.findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
etOrigin.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
etOrigin.setOnItemClickListener(this);
etDestination.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
etDestination.setOnItemClickListener(this);
return Myview;
}
//**********For changing colors in the directions************************************************************/
/**************************************************************************************************************/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
goToLocationZoom(9.3068, 123.3054, 15);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
LatLngBounds Dumaguete = new LatLngBounds(new LatLng(9.267, 123.264), new LatLng(9.33, 123.311));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMinZoomPreference(15.0f);
mMap.setMaxZoomPreference(20.0f);
mMap.setLatLngBoundsForCameraTarget(Dumaguete);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Dumaguete.getCenter(), 15));
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
private void goToLocationZoom(double lat, double lng, int zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(getActivity(),"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
private void sendRequest() {
String origin = etOrigin.getText().toString();
String destination = etDestination.getText().toString();
if (origin.isEmpty()) {
Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show();
return;
}
try {
new DirectionFinder(this, origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline : polylinePaths) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
Toast.makeText(getActivity(), "Directions found!", Toast.LENGTH_SHORT).show();
for (final Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) Myview.findViewById(R.id.tvDistance)).setText(route.distance.text); //For Distance
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
/******************For Changing color ********************************************************/
mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
#Override
public void onPolylineClick(Polyline polyline) {
// Flip the values of the red, green and blue components of the polyline's color.
polyline.setColor(polyline.getColor() ^ 0x00ffffff);
// Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
}
});
/*************************************************************************************************/
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258));
/**/
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).color(color).width(15).clickable(true);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(getActivity(), 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(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&types=establishment&strictbounds&location=9.30684,123.305447&radius=2000");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
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 {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return String.valueOf(resultList.get(index));
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
// mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}//End of CLass ThirdFragment.java
This is my Data Parsing and how do I change it to also get the distance of the alternate routes?
DirectionFInder.java
import android.os.AsyncTask;
import com.google.android.gms.maps.model.LatLng;
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.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class DirectionFinder {
private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?";
private static final String GOOGLE_API_KEY = "AIzaSyC1E8NU2jjoQF7dN37bIOz_1fy0fe98YhI";
private DirectionFinderListener listener;
private String origin;
private String destination;
public DirectionFinder(DirectionFinderListener listener, String origin, String destination) {
this.listener = listener;
this.origin = origin;
this.destination = destination;
}
public void execute() throws UnsupportedEncodingException {
listener.onDirectionFinderStart();
new DownloadRawData().execute(createUrl());
}
private String createUrl() throws UnsupportedEncodingException {
String urlOrigin = URLEncoder.encode(origin, "utf-8");
String urlDestination = URLEncoder.encode(destination, "utf-8");
return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination +"&alternatives=true" +"&key=" + GOOGLE_API_KEY;
}
private class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.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 = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}
return decoded;
}
}
This is the screenshot of the application.
The dark green color is the main route and the pink and blue are the alternate routes. How can I get the distance of the pink and blue as well? Please help.
You are already looping through all of the routes, so storing the distance for each route should be simple. This line of code is where you get the distance for each route:
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));'
If you create an array, you can store the value of each route during each iteration of the loop. Let's say you have an array called routeDistances[]. You could do something like this:
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
routeDistances[i] = jsonDistance.getInt("value"); // add this line
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
The line of code will allow you to store the distance for each route. You can then get the distance using the array. For example routeDistances[0] will have the distance for the first route, routeDistances[1] will have the distance for the next route etc.
I want to remove all the markers and remove setInfoWindowAdapter when i refresh the maps. But the app will crash if i refresh it.
Here's my code
private final BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
//Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
new GetInfo().execute(Config.INFO_URL);
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
//Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
new GetInfo().execute(Config.INFO_URL);
}
}
}
};
class GetInfo extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MapsActivity.this);
dialog.setMessage("Mohon tunggu");
dialog.setTitle("Mendapatkan data...");
dialog.show();
dialog.setCancelable(true);
}
#Override
protected Boolean doInBackground(String... urls) {
array.clear();
mMarkersHashMap.clear();
mMyMarkersArray.clear();
markerPoints.clear();
targets.clear();
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray konten = jsono.getJSONArray("konten");
mMarkersHashMap = new HashMap<Marker, MyMarker>();
for (int i = 0; i < konten.length(); i++) {
HashMap<String,String> newMap=new HashMap<String,String>();
JSONObject object = konten.getJSONObject(i);
newMap.put("nama", object.getString("nama"));
newMap.put("deskripsi",object.getString("deskripsi"));
newMap.put("foto",object.getString("foto"));
newMap.put("marker", object.getString("marker"));
newMap.put("lat",object.getString("lat"));
newMap.put("lng",object.getString("lng"));
array.add(newMap);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(final Boolean result) {
dialog.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!result) {
//Toast.makeText(getApplicationContext(), "Tidak dapat mengambil data dari server, silahkan cek koneksi internet anda", Toast.LENGTH_LONG).show();
showInfo();
}
else {
for (int i = 0; i < array.size(); i++) {
HashMap<String, String> newMap = new HashMap<String, String>();
newMap = array.get(i);
mMyMarkersArray.add(new MyMarker(newMap.get("nama"), newMap.get("deskripsi"), newMap.get("foto"), newMap.get("marker"), Double.parseDouble(newMap.get("lat")), Double.parseDouble(newMap.get("lng"))));
}
plotMarkers(mMyMarkersArray);
}
}
});
}
}
Here's the plotMarkers
public void plotMarkers(ArrayList<MyMarker> markers) {
if(markers.size() > 0) {
for (MyMarker myMarker : markers)
{
dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
markerOption = new MarkerOptions().position(dest);
location_marker = mMap.addMarker(markerOption);
Target target = new PicassoMarker(location_marker);
targets.add(target);
ImageView image = new ImageView(this);
image.setImageResource(R.mipmap.marker);
int width = image.getDrawable().getIntrinsicWidth();
int height = image.getDrawable().getIntrinsicHeight();
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(width, height).onlyScaleDown().into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if(i.getBooleanExtra("maps", true)) {
location_marker.setTitle(i.getStringExtra("nama"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dest, 16));
}
else {
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
Here's the refresh menu on action bar
case R.id.action_refresh:
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
return true;
What's wrong with my code?
I'm assuming you still have similar implementation from before.. In order to remove all Markers. You could just call Marker.remove() on the marker instance. In your case, you put the marker instance in a HashMap. So what you could do is something like this:
private void removeAllMarkers() {
// hmap here is the HashMap you have.
for (HashMap.Entry<Marker, MyMarker> entry : hmap.entrySet()) {
entry.getKey().remove();
}
}
This iterates over the HashMap where you add the Markers in plotMarkers function and remove them all. Just call this function in the code where you refresh the Map.
Regarding your concern with the setInfoWindowAdapter, if you're pertaining to the InfoWindow of the Marker, I think so long as you are able to remove the Marker itself, you'll no longer have a problem with it.
Found this answer that shows how to remove a marker. I think this post on iterating over hashmaps would also be helpful for you.
In my app I want to show the multiple marker using latitude and longitude from JSON but when I run the application it only shows one marker, other markers are not shown. Please help - here is my code:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Loading...", "Please wait for few seconds");
// dialog = new ProgressDialog(getActivity().this);
// dialog.setMessage("Loading, please wait");
// dialog.setTitle("Connecting server");
// dialog.show();
// dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// Date a = new Date();
// a.setTime(System.currentTimeMillis()-(60*60*1000));
// Log.e("onehourback",""+a);*/
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("SingleIMEs");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Log.e("object",""+object);
/*try {
array.add(jarray.getJSONObject(i));
Log.e("array",""+array);
} catch (JSONException e)
{
e.printStackTrace();
}*/
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
}
}
//}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
/* adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
*/
}
}
private void setUpMapIfNeeded(View inflatedView) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(latt,lng)).title("eee"));
Log.e("lat",""+latt);
Log.e("lon",""+lng);
mMap.setMyLocationEnabled(true);
if (mMap != null) {
//setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("WePOP"));
// mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position( new LatLng(Double.parseDouble(datas.get("Lat")), Double.parseDouble(datas.get("Long")))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
It looks like you're overwriting your latt and lng variables multiple times in this code:
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
I would suggest you create a List that holds some sort of object containing latt and lng information (something like List positions).
Then modify your code in setUpMapIfNeeded to cycle through all your LatLngs. Something like this:
for(LatLng latlng: positions) {
mMap.addMarker(new MarkerOptions().position(new LatLng(latlng.getLat(),latlng.getLng())).title("eee"));
Log.e("Added marker at lat: " + latlng.getLat() + ", lng: " + latlng.getLng());
}
Notice: It's been quite some time since i've used android and google maps, so the code i've written here probably isn't perfect - but the idea should be good :-)
In my application I want to track the vehicles,am getting multiple latitude and longitude from JSON I plotted the latlong in the google map,when the latlong changes in JSON the marker has to move.but here it moves by creating an new marker the previous marker is still exist.how can I remove the marker in the previous location
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
mMap.clear();
if (marker != null) {
marker.remove();
}
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
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();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
//arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
// pubname = json.getString("PubName");
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
// map.put("PubName", json.getString("PubName"));
//map.put("PubID", json.getString("PubID"));
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
if (marker != null) {
marker.remove();
}
Do you actually have a function to remove the marker here? If not, you have to remove the marker from the map and set it to null in order to remove it.
marker.setMap(null);
Source: marker API documentation
I am trying to get the latitude, longitude, current address, current speed and send to the server for every 5 min. I can get the lat, long, address. But I can not get the current speed from location.getSpeed().
Herewith I have attached my entire code. Please review and give me your valuable suggestions to resolve my problem
public class MainActivity extends FragmentActivity implements LocationListener {
private GoogleMap googleMap;
private LocationManager locationManager;
private String provider;
Location location;
UserSessionManager session;
private Handler customHandler = new Handler();
String currentdatetime_tosend, latitude_tosend, logitude_tosend,
address_tosend, speed_tosend, username_tosend, startTime_tosend;
Boolean isInternetAvail = false;
ConnectionCheck conChk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(GlobalConstants.loginDriverName);
System.out.println("GlobalConstants.loginDriverName==> "+GlobalConstants.loginDriverName);
session = new UserSessionManager(getApplicationContext());
try {
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
conChk = new ConnectionCheck(getApplicationContext());
GetLocaion();
} catch (Exception e) {
e.printStackTrace();
}
}
private void AddMarker(double latitude, double longitude, String driverName) {
googleMap.clear();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(driverName);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_car));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Double lat = (Double) (location.getLatitude());
Double lng = (Double) (location.getLongitude());
speed_tosend = Float.toString(location.getSpeed());
Toast.makeText(getApplicationContext(),
"Speed==> " + speed_tosend.toString() + "",
Toast.LENGTH_SHORT).show();
latitude_tosend = lat.toString();
logitude_tosend = lng.toString();
getAddress();
AddMarker(lat, lng, GlobalConstants.loginDriverName);
if (conChk.isConnectingToInternet())
new SendDetailsInBackground().execute();
} else
Toast.makeText(getApplicationContext(),
"Getting Location.. Please Wait..", Toast.LENGTH_SHORT)
.show();
}
private void BackgroundProcess() {
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
GetLocaion();
customHandler.postDelayed(this, 30000);
}
};
private void StartTheProcess() {
BackgroundProcess();
}
private void StopGetingLocation() {
customHandler.removeCallbacks(updateTimerThread);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
private void GetLocaion() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
Toast.makeText(getApplicationContext(), "Location Activated",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"No location found..!!", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "GPS IS Ennabled..!!",
Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.startGettingLocation) {
startTime_tosend = getDateTime();
StartTheProcess();
return true;
}
if (id == R.id.stopGetingLocation) {
StopGetingLocation();
return true;
}
if (id == R.id.logout) {
exit();
}
return super.onOptionsItemSelected(item);
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
class SendDetailsInBackground extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("currentdatetime",
startTime_tosend));
params.add(new BasicNameValuePair("driver_mobile",
GlobalConstants.loginDriverNumber));
params.add(new BasicNameValuePair("username",
GlobalConstants.loginDriverName));
params.add(new BasicNameValuePair("lattitude", latitude_tosend));
params.add(new BasicNameValuePair("longtitude", logitude_tosend));
params.add(new BasicNameValuePair("currentaddress", address_tosend));
params.add(new BasicNameValuePair("currentspeed", speed_tosend));
String json = sendToServer(GlobalConstants.url_pass_tripdetail,
params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String file_url) {
}
}
public String sendToServer(String url, List<NameValuePair> params) {
String TAG = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity);
System.out.println("Response==> " + response);
TAG = response;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return TAG;
}
private void getAddress() {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
Double.parseDouble(latitude_tosend),
Double.parseDouble(logitude_tosend), 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i) + ",");
Toast.makeText(getApplicationContext(), "Address Found..!!!",
Toast.LENGTH_LONG).show();
address_tosend = sb.toString();
} else {
Toast.makeText(getApplicationContext(), "Address is empty!",
Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No Address returned!",
Toast.LENGTH_SHORT).show();
}
}
public void exit() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Logout")
.setMessage("Are you sure you want to Logout?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
session.logoutUser();
StopGetingLocation();
finish();
}
}).setNegativeButton("No", null).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}