i have develop app that when run take the city name by lat and long using a GPSTracker.java class and add this city name to url for retrive json data.
My code works very fine from API 18 to API 22 but now when i run my code on API 23 the geocoder doesn't work and city name is null
This is my code on Main Activity for retrive city name:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
String cityName = null;
Geocoder gcd = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
Log.d("nome_cit", "debug_cit " + cityName);
// Controllo formattazione nomi Car2Go
if(cityName.equals("Rome")) {
nome_citta = "Roma";
}else if (cityName.equals("Florence")){
nome_citta = "Firenze";
}
else if (cityName.equals("Milan")){
nome_citta = "Milano";
}
else if (cityName.equals("Turin")){
nome_citta = "Torino";
}else if (cityName.equals("New York")){
nome_citta = "NewYorkCity";
}else if (cityName.equals("Los Angeles")){
nome_citta = "LosAngeles";
}
else if (cityName.equals("San Diego")){
nome_citta = "SanDiego";
}
else if (cityName.equals("Twin Cities")){
nome_citta = "TwinCities";
}
else if (cityName.equals("Vienna")) {
nome_citta = "wien";
}
else if (cityName.equals("Munich")) {
nome_citta = "München";
}
else if (cityName.equals("Osler")) {
nome_citta = "Rheinland";
}
// Controllo formattazione JCDecaux
else if (cityName.equals("Valencia")) {
nome_citta_test = "Valence";
}
else if (cityName.equals("Parigi")) {
nome_citta_test = "Paris";
}
else if (cityName.equals("Besançon")){
nome_citta_test = "Besancon";
}
else if (cityName.equals("Créteil")) {
nome_citta_test = "Creteil";
}
else {
nome_citta = cityName;
nome_citta_test = cityName;
}
}
else {
}
} catch (IOException e) {
e.printStackTrace();
}
on my map for my position i have set this permission:
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
.PERMISSION_GRANTED) {
/*Toast.makeText(getActivity(),
"Need location permission for map.setMyLocationEnabled(true);",
Toast.LENGTH_LONG).show();*/
MultiplePermissionsListener snackbarMultiplePermissionsListener =
SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
.with((ViewGroup) getView(), "La app ha bisogno di ablitare i permessi di localizzaione per mostrare la mappa")
.withOpenSettingsButton("Settings")
.withCallback(new Snackbar.Callback() {
#Override
public void onShown(Snackbar snackbar) {
// Event handler for when the given Snackbar has been dismissed
}
#Override
public void onDismissed(Snackbar snackbar, int event) {
// Event handler for when the given Snackbar is visible
}
})
.build();
Dexter.checkPermissions(snackbarMultiplePermissionsListener, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.GET_ACCOUNTS);
return;
}
and this is my GPSTracker.java class:
public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Function to get the user's current location
*
* #return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
location=null;
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
// DecimalFormat latitude = new DecimalFormat("00.00");
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(R.string.title);
// Setting Dialog Message
alertDialog
.setMessage(R.string.subtitle);
// On pressing Settings button
alertDialog.setPositiveButton(R.string.impostazioni,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton(R.string.cancella,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setCancelable(false);
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Also i have notice that using place picker on API 23 i recive this error:
Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
for this code:
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
String addresses = place.getAddress().toString();
if (addresses != null) {
puntoA.setText(addresses);
}if (addresses.isEmpty()){
addresses = "(" + place.getLatLng().latitude + "," + place.getLatLng().longitude + ")";
puntoA.setText("nessun indirizzo disponibile " + addresses);
}
//puntoA.setText(addresses);
// Recupero coordinate
Geocoder geocoder = new Geocoder(getActivity());
List<Address> address = null;
try {
address = geocoder.getFromLocationName(addresses, 1);
} catch (IOException e) {
e.printStackTrace();
}
if(address.size() > 0) {
Lat = address.get(0).getLatitude();
Lon = address.get(0).getLongitude();
}
else if (address.size() == 0) {
Lat = place.getLatLng().latitude;
Lon = place.getLatLng().longitude;
}
but also this function works very well on other API version
Any help please?
now my code works fine on API 23 and i use this code:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
Double LatFab = gpsTracker.getLatitude();
Double LonFab = gpsTracker.getLongitude();
List<Address> geocodeMatchess = null;
String Country_;
try {
geocodeMatchess = new Geocoder(getActivity(), Locale.ENGLISH).getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (geocodeMatchess.isEmpty()) {
}else {
Country_ = geocodeMatchess.get(0).getLocality();
citta_fab = Country_;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hope this hel you
Related
I want to calculate distance between two location one which is fixed and second one is user's location.
Here is my Activity where I want to calculate distance.
public class CalDist extends AsyncTask<String, Void, String> {
protected void onPreExecute(){
}
protected String doInBackground(String... arg0) {
StringBuilder stringBuilder = new StringBuilder();
Double dist = 0.0;
try {
//destinationAddress = destinationAddress.replaceAll(" ","%20");
//String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+fromLatitude+","+fromLongitude+"&destination=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=AIzaSyBpFhiStQvyV5dbVXmarXhzhvGgGFOfubM";
//String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + fromLatitude + "," + fromLongitude + "&destination=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=AIzaSyBpFhiStQvyV5dbVXmarXhzhvGgGFOfubM";
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ fromLatitude + "," + fromLongitude + "&destinations=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=HereIsMyAPIKey";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
Log.i("Distance", distance.toString());
dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );
//Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Double.toString(dist);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(Payment.this, "ResultCalcDist:" +result, Toast.LENGTH_SHORT).show();
}
Here is how I am calling function.
new CalDist().execute();
Two points for distance calculation.
gps = new GPSTracker(Payment.this);
fromLatitude = gps.getLatitude();
fromLongitude = gps.getLongitude();
toLatitude = 23.1914909;
toLongitude = 72.630121;
Here is my GPS tracker from where I am getting latitude and longitude.
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
final private int REQUEST_LOCAION = 12;
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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.
android.support.v13.app.ActivityCompat.requestPermissions((Activity)getApplicationContext(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCAION);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
else
{
showSettingsAlert();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCAION: {
if ((grantResults.length > 0) && (grantResults[0] +
grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
//Call whatever you want
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}
Please help me with this.
I am developing an app where users will be reporting field Incidences.
The Incident location(longitude and latitude) is important for mapping purposes.
For better, i want to use GPS provider only.
In my activity, i have a nested class for getting location information.
private class myGPSTracker extends Service implements LocationListener {
public myGPSTracker() {
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
//isNetworkEnabled = locationManager
// .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled ) {
// no network provider is enabled
showSettingsAlert();
canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if ( ActivityCompat.checkSelfPermission(ReportIncident.this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(ReportIncident.this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, ACCESS_FINE_LOCATION );
}
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} else {
canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if ( ContextCompat.checkSelfPermission(ReportIncident.this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(ReportIncident.this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, ACCESS_FINE_LOCATION );
}
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public double getAltitude()
{
if(location != null){
altitude = location.getAltitude();
}
// return longitude
return altitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public String getAddress()
{
Geocoder geocoder =
new Geocoder(context, Locale.getDefault());
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(this.getLatitude(),
this.getLongitude(), 1);
} catch (Exception e1) {
e1.printStackTrace();
return ("Un Known place!");
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available),
* city, and country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ?
address.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "Un known place";
}
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ReportIncident.this);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
In my Activity, i try to get location information by
gpstracker=new myGPSTracker();
Incidents incidents =new Incidents();
incidents.setId(new Date().getTime());
incidents.setIncidentdate(new Date().getTime());
incidents.setPlaceName("Some Thing");
incidents.setAltitude(gpstracker.getAltitude());
incidents.setMyLat(gpstracker.getLatitude());
incidents.setMyLongtitude(gpstracker.getLongitude());
When i run the app, i get 0 for longitude and latitude, and i also debugged and found out the location manager is null.
Here is the complete code for the activity.
public class ReportIncident extends Activity {
Button bb;
double mylat;
double mylong;
String myplace;
double myalt;
EditText editText;
private Context context;
//private Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
private myGPSTracker gpstracker;
Location location; // location
double latitude; // latitude
double longitude; // longitude
double altitude;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
private static final int ACCESS_FINE_LOCATION = 200;
//private Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_incident);
context=getApplicationContext();
gpstracker=new myGPSTracker();
editText=(EditText)findViewById(R.id.txtReportIncident);
bb=(Button)findViewById(R.id.btnReport);
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mydescription=editText.getText().toString().trim();
if(TextUtils.isEmpty(mydescription))
{
editText.setError("Field can not be blank");
return;
}
Incidents incidents =new Incidents();
incidents.setId(new Date().getTime());
incidents.setIncidentdate(new Date().getTime());
incidents.setPlaceName("Some Thing");
incidents.setAltitude(gpstracker.getAltitude());
incidents.setMyLat(gpstracker.getLatitude());
incidents.setMyLongtitude(gpstracker.getLongitude());
incidents.setIncidentDescription(mydescription);
new AddIncidentAsyncTask(getApplicationContext()).execute(incidents);
editText.setText("");
}
});
}
What is missing?
Any help will be highly appreciated.
Ronald
I am developing an application which enable GPS and get the current location. My code is working fine in all android version expect API 23 i.e. Marshmallows. I am testing in Nexus 5 (API 23), Galaxy Note 3 (API 22).
Here is my code
public void program()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(NearBy.this);
builder.setTitle("Location Service is Not Active");
builder.setMessage("Please Enable your location services").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
final String cityName = addresses.get(0).getAddressLine(0) + " ";
String stateName = addresses.get(0).getAddressLine(1) + " ";
String countryName = addresses.get(0).getAddressLine(2) + " ";
String country = addresses.get(0).getCountryName() + " ";
String Area = addresses.get(0).getSubAdminArea() + " ";
String Area1 = addresses.get(0).getAdminArea() + " ";
String Area2 = addresses.get(0).getLocality() + " ";
String Area3 = addresses.get(0).getSubLocality();
Log.e("Locaton", cityName + stateName + countryName + country + Area + Area1 + Area2 + Area3);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
I am getting NullpointerException at
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
only in Nexus 5 (API 23). I also granted permission (ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION) in both Mainfest and also during run time.
Kindly provide solution for this.
UPDATED
I have changed my code. I created a GPSTracker class and I am getting lat, Lng as 0
GPSTracker.java
public class GPSTracker extends Activity implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
#TargetApi(Build.VERSION_CODES.M)
public void stopUsingGPS() {
if (locationManager != null) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location currentLocation) {
this.location = currentLocation;
getLatitude();
getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Problem
The location obtained may be null if the last know location could not be found due to various reasons. Read about it in the docs [here][2]
Reason/How i debugged it
getFromLocation does not throws a nullpointer according to documentation hence the problem is in your location object.
Read here about this method
Remedy
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Check if the location obtained in the above step is NOT NULL and then proceed with the geocoder.
Code snippet
...
else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location == null) {
log.d("TAG", "The location could not be found");
return;
}
//else, proceed with geocoding.
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
Fetching the location - An example
Read here
Complete code
View it here
First In marshmallow add all permission on run time also. Otherwise Please restart your mobile and then check again.
I have a GPSTracker file but in the android M iam geting a zero on the locations... i ask for your help to solve this problem...see the code below
Fragment with the location and a webview to google maps
public class ComoChegar extends Fragment {
EmpresaID item;
public ComoChegar() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_como_chegar, container, false);
Bundle id = getActivity().getIntent().getExtras();
String Filial = id.getString("filial");
if (isOnline()) {
item = new EmpresaID(Filial);
Autenticado(item);
}
else
{
android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
alerta.setPositiveButton("OK", null);
alerta.show();
}
return tela;
}
public void Autenticado(EmpresaID id)
{
ServerRequests server = new ServerRequests(getActivity());
server.getEmpresa(id, new GetEmpresaID() {
#Override
public void done(EmpresaID empresa) {
if(empresa == null) {
Erro();
}
else {
GPSTracker gps = new GPSTracker(getActivity());
List<Address> addresses;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Geocoder geocoder;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
if(latitude == 0 && longitude == 0)
{
gps.showSettingsAlert();
}
else {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
String saida = "" + address + "," + city + "-" + postalCode;
String chegada = "" + empresa.endereco + " " + empresa.numero + "," + empresa.bairro + "-" + empresa.cidade;
WebView mapa = (WebView) getActivity().findViewById(R.id.mapa);
mapa.setWebViewClient(new WebViewClient());
mapa.getSettings().setJavaScriptEnabled(true);
String ida = saida.replace(" ", "+");
String trem = chegada.replace(" ", "+");
String Url = "https://www.google.com/maps/dir/" + latitude + "," + longitude + "/" + trem + "";
mapa.loadUrl(Url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void Erro() {
android.support.v7.app.AlertDialog.Builder alerta = new android.support.v7.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Erro ao Carregar dados do servidor");
alerta.setPositiveButton("OK", null);
alerta.show();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
the GPSTracker class
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Erro");
// Setting Dialog Message
alertDialog.setMessage("GPS não está ligado. Gostaria de Checar nas Configurações?");
// On pressing Settings button
alertDialog.setPositiveButton("Configurações", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Since your LocationListener tries to get location using only Network not GPS, with this code snippet: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
probably you are getting latitude and longitude values but with a delay. I had the same problem then I begin to use new/latest Location service API and use:
GoogleApiClient.
First you need to implement
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
from you activity that want to fetch the location data.
Define
private GoogleApiClient mGoogleApiClient;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
If you haven't add
<uses-permission `android:name="android.permission.ACCESS_FINE_LOCATION"/>`
to the manifest file, add that.
For further documentation : https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient
I am currently developing an Android app which prompts the user to enable GPS if it's not on and I have used AlertDialog for this purpose. After I enable the GPS from settings and come back to my app by pressing back button, the mapView doesn't reflect my current location. Although If I have my GPS on before running the app, the app properly displays my location. I want to know to which method to use for this refresh user location after enabling GPS purpose. Any relevant article would really help.
Following is my code for the GPS part:
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/******/
/****/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
The following class makes use of above class to display location in a mapView
LocationActivity.java
public class LocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnSendAddress;
Button find_rick;
TextView tvAddress;
AppLocationService appLocationService;
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
//Google maps implementation
GoogleMap googleMap;
private static final String TAG = LocationActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_layout);
createMapView();
btnShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnSendAddress = (Button) findViewById(R.id.btnSendAddress);
gps = new GPSTracker(LocationActivity.this);
// Check if GPS enabled and if enabled after popup then call same fn
MapMyCurrentLoction();
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MapMyCurrentLoction();
}
});
btnSendAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tag_string_req_send_data = "req_send";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_AUTOWALA_DHUNDO, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Autowala Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
Log.d("Autowale ka data","success");
} else {
// Error occurred in data sending. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Data sending Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data_send");
params.put("latitude", Double.toString(gps.getLatitude()));
params.put("longitude", Double.toString(gps.getLongitude()));
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req_send_data);
}
});
}
#Override
protected void onPause(){
super.onPause();
MapMyCurrentLoction();
//super.onResume();
}
#Override
protected void onResume(){
super.onResume();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
//super.onResume();
}
private void createMapView(){
/**
* Catch the null pointer exception that
* may be thrown when initialising the map
*/
try {
if(null == googleMap){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if(null == googleMap) {
Toast.makeText(getApplicationContext(),
"Error creating map",Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
}
/**
* Adds a marker to the map
*/
private void addMarker(double lat,double lng){
/** Make sure that the map has been initialised **/
if(null != googleMap){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat,lng))
.title("Your Location")
.draggable(true)
);
//zooming to my location
float zoomLevel = 16.0F; //This goes up to 21
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, zoomLevel);
googleMap.animateCamera(yourLocation);
}
}
private void MapMyCurrentLoction(){
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
/*------- To get city name from coordinates -------- */
String area = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addressList = null;
try {
addressList = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
area = sb.toString();
}
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\n"+area, Toast.LENGTH_SHORT).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
//Again search and map my location after enabling gps
}
}
}
You just need to initialize this
gps = new GPSTracker(LocationActivity.this);
at onResume() and at onCreate() and if needed then at onRestart() too.
This is not the correct way but for making it working you can do this.
you`re probably interest in 'onResume' method. After getting back to Activity this one is invoked. Sho in there you should update the position