I am working with a project to get latitude and longitude and also send that lat and long to my server. But I didn't get the latitude and longitude. I cannot find out where the error occur.
private String Tag="MainActivity";
String lat="", lon="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLocation = (Button)findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.txtLoc);
tv.setText("Your Location is:" + lat + "--" + lon);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
});
Button btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
postData(lat, lon);
}
});
}
public void postData(String la, String lo) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet htget = new HttpGet("http://192.168.1.2/.../"+la+"/"+lo);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(htget);
String resp = response.getStatusLine().toString();
Toast.makeText(this, resp, Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
Get lastKnowLocation from provider - GPS:
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
You parsing of String from Double is incorrect, Try to parse:
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
tv.setText("Your Location is:" + lat + "--" + lon);
try to use
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
instead
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
Hope this vl work for you :-)
Related
I am trying to get the latitude and longitude of the current location using the following:
GoogleMap map;
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
lat = map.getMyLocation().getLatitude();
lng = map.getMyLocation().getLongitude();
For some reason the last two lines are causing the app to crash due to a NullPointerException. What am I doing wrong?
The biggest thing that bugs me about this is the fact that map.setMyLocationEnabled(true); does indeed set my current location.
Thanks to anyone looking at this
Try this:
public Double Lat = null;
public Double Lng = null;
String LatLng = null;
private LocationClient mLocationClient;
in your onCreateView() add this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.yourLayout, container, false);
mLocationClient = new LocationClient(getActivity(), this, this);
rootView.findViewById(R.id.ATestButton).setOnClickListener(
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
Lat = currentLocation.getLatitude();
Lng = currentLocation.getLongitude();
LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
Toast.makeText(getActivity(), LatLng, 0).show();
});
Look at my complete github for a working example.
// I would a test button so can click it to see if anything is returned.
public void turnGPSOn() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) {
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
void getLocation()
{
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
turnGPSOn();
}
try {
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10,
locationListener);
} catch (Exception ex) {
}
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String latLongString = "";
try {
if (location != null) {
Log.e("test", "gps is on send");
latitude = Double.toString(location.getLatitude());
longitude = Double.toString(location.getLongitude());
Log.e("test", "location send");
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
Log.w("CurrentLocLatLong", latLongString);
} else {
latLongString = "No location found";
}
} catch (Exception e) {
}
}
Your app is crashing because
map.getMyLocation()
returns null if there is no location data available.So you can have !=null check like this
if( map.getMyLocation() !=null){
lat = map.getMyLocation().getLatitude();
lng = map.getMyLocation().getLongitude();
}
Also this method is deprecated, so you should use FusedLocationProviderApi instead. See official documentation here
Here is a very good implementation of FusedLocation Api, you can check out that too.
map.getMyLocation() is null
you should check for that condition
I have found a solution. While I am still not sure why the other methods is giving me a null pointer, the below works just fine and will suit my needs.
LocationManager locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locman .getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lng = location.getLongitude();
double lat = location.getLatitude();
I want to get current longitude and latitude as int
So I use this code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
....Notify
}
if (gps_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
if (network_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
locationManager.removeUpdates(this);
Unfortunately longitude and latitude are always null.
I have all permission needed in the manifest.
How can I fix this issue?
Well this is what i use for location listener
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class LocationUtils implements LocationListener{
Context context;
private String provider;
private LocationManager locationManager;
private String latitude="no value";
private String longitude="no value";
public LocationUtils(Context context) {
this.context=context;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
latitude="no value";
longitude="no value";
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
/*Toast.makeText(context, "Provider " + provider + " has been selected.",
Toast.LENGTH_SHORT).show();*/
// System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
/*Toast.makeText(context, "Location not available",
Toast.LENGTH_SHORT).show();*/
}
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latitude = lat + "";
longitude = lng + "";
/* Toast.makeText(context, " lat: "+lat +" Long:"+lng,
Toast.LENGTH_SHORT).show(); */
}
#Override
public void onProviderDisabled(String provider) {
//Toast.makeText(context, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
//Toast.makeText(context, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
Now in your activity u can get
LocationUtils appLocationManager = new LocationUtils(getContext());
String latitude = appLocationManager.getLatitude();
String longitude = appLocationManager.getLongitude();
Also add
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in your manifest file
First check the GPS enabled in your device.
Check all the permissions included in the manifest
You are fetching the last known location using the GPS provider so remove that line and fetch the location individually for both the provider(There should be possible that your GPS is not available at that time so you did not get the location and you are fetching the last known location using the GPS so it can be null and if location will be null then it will not goes inside the conditions like if(network_enabled) and if(gps_enabled).).
In short check the Last known location of GPS if it is null then try to get the location using the Location provider and use that location.
public class SMS_Service extends Service {
private final String LOGTAG = "SMS_Service";
String latLongString;
String addressString;
double altitude;
int LAC;
int mcc = 0;
int mnc = 0;
String pn_no;
Altitude_Details ld = new Altitude_Details();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e(LOGTAG, "created");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e(LOGTAG, "destroyed");
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e(LOGTAG, "started");
SmsManager sms = SmsManager.getDefault();
// get phone number from shared preference
SharedPreferences default1 = getSharedPreferences("Device",
MODE_WORLD_WRITEABLE);
pn_no = default1.getString("Phone_NO", "");
Log.e("phone_no in sms service", pn_no);
String From = intent.getStringExtra("From");
String Msg = intent.getStringExtra("Msg"); // get message from intent
Log.e("ON start:", "" + From);
Log.e("ON start:", "" + Msg);
String number = From.substring(7, 11);
Log.e("ON start: SUBSTRING", "" + number);
// check msg for Location keyword match or not
if (Msg.equals("LOCATION") && pn_no.equals(number)) {
Log.e("location:", "Location found");
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
// find MNC and MCC
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
Log.e("MCC", "" + mcc);
Log.e("MNC", "" + mnc);
}
// find LAC for GSM
if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) tel
.getCellLocation();
if (location != null) {
LAC = location.getLac();
Log.e("cell location", "LAC: " + location.getLac()
+ " CID: " + location.getCid());
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
// update method return latest location
updateWithNewLocation(location);
// location change then listner called
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
// send mcc,mnc,latitude,longitude,altitude,address,Link in message
String Url = "http://itouchmap.com/latlong.html";
sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc
+ "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString
+ "\nAltitude:" + altitude + "feet"
+ "\nGo to Below site:\n" + Url, null, null);
sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString,
null, null);
// stop service automatically
SMS_Service.this.stopSelf();
}
else {
Log.e("loation:", "Location not found");
SMS_Service.this.stopSelf();
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
addressString = "\nno address found";
// check location get or not from provider
if (location != null) {
// get latitude and longitude
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLongString = "\nLat:" + latitude + "\nLong:" + longitude;
Log.e("location", "" + latLongString);
// get altitude from method
altitude = ld.getElevationFromGoogleMaps(latitude, longitude);
Log.e("Altitude", "" + altitude);
// find address from latitude and longitude
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 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)).append("\n");
}
addressString = sb.toString();
Log.e("Address", "" + addressString);
} catch (IOException e) {
}
} else {
latLongString = "\n No location found";
Log.e("location", "" + latLongString);
}
}
}
hey you can make the service and use this code to get altitude and latitude and decode this using class
Try This code
double longitude,latitude;
int lon,lat;
getcurrentloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show();
}else{
LocationResult locationResult=new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
longitude=location.getLongitude();
latitude=location.getLatitude();
lon=(int)longitude;
lat=(int)latitude;
Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(GpsLocationFinder.this, locationResult);
}
}
});
And the MyLocation Class is Below
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
double longitude,latitude;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
//Log.e("GPS DISTANCE","GPS Enabled");
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
//don't start listeners if no provider is enabled
//try{
try{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
I try to add a location from the GPS but i always get null. Can you please help and show me what I did wrong?
I would like to always receive the location in onCreate. If no location is received
"No provider received" appears instead of the location. The problem is i always get the message.
//Location variables
private TextView gps;
private LocationManager locationManager;
private String locationProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_draw);
initializeData();
}
private void initializeData()
{
gps = (TextView) findViewById(R.id.GPS);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = locationManager.getBestProvider(new Criteria(), true);
if(locationProvider!=null)
{
gps.setText("Upload image location: "+ locationProvider);
}
else
{
gps.setText("Upload image location: No provider Found" );
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
private void showLocation(Location location)
{
if(location==null)
gps.append("\nUnknown location");
else
{
double lat = location.getLatitude();
double lng = location.getLongitude();
gps.append("\n\nLocation lat: " +lat+
", long: " + lng+"\n"
+ getAddress(lat, lng));
}
}
public void onLocationChanged(Location location) {
showLocation(location);
}
public void onProviderDisabled(String provider) {
gps.append("\nProvider Disabled: " +provider);
}
public void onProviderEnabled(String provider) {
gps.append("\nProvider Enabled: " +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
gps.append("\nProvider Status Changed: " + provider+ ",status: "+
status);
}
public String getAddress(double lat, double lng)
{
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String str = obj.getCountryName();
str+="\n" + obj.getCountryCode();
str+="\n" + obj.getLocality(); //current city
str+="\n" + obj.getAddressLine(0);
return str;
}
catch (IOException e) {
return "Error: " +e.getMessage();
}
}
1)You need to request updates from provider:
newLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, "error string");
2)Register a Listener:
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Do something
} );}
I am using the following code to find current location of user
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
public void onLocationChanged(Location location) {
Log.e("changed","location");
// TODO Auto-generated method stub
showLocation(location);
}
But the location of user is not finding.If i change provider to Network Provider its working.But with GPS provider only it not working.
change the requestLocationUpdates method so that it updates faster and with less change in coordinates. Change it to:-
requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Try it now. If possible move the phone some meters so that it is detected soon by the GPS satellites. I am presuming that GPS is switched on.
GPS does not provide a 'get my location on demand' functionality. You have to be patient and wait until the device gets a fix from several satellites. This may take several minutes, even with a clear view of the sky. This is why the OS implements this as a callback. onLocationChanged runs when the device has a fix and you just have to wait for it.
Will you please elaborate more? Do you need to find the current location in mapview by Long or Lat? If this is your question then do one thing :
Find Lat and Long by sending manually through DDMS or by generating Lat and Lang on click at mapview :
It can be done by:
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.MakeTest(getApplicationContext(),Text,Toast.Length_Long).show()
}
So by this you can get your lat and Long.After getting Lat and Long at mapView's click listener you can write below code:
Projection proj = view1.getProjection();
GeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
//Getting Lat and Log
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
GeoPoint point = new GeoPoint( (int) (loc.getLatitudeE6()),(int) (loc.getLongitudeE6()));
//Getting location from lat and Long
String address="";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
Toast t =Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude+" name: "+address, Toast.LENGTH_LONG);
t.show();
You will get output as you click at mapview.
For click event on MapView please write above code in dispatchTouchEvent() as
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_UP:
//write above code here
}
}
Try this one.
Edit: Check your code with this given below code.
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
latituteField.setText(String.valueOf(loc.getLatitude()));
longitudeField.setText(String.valueOf(loc.getLongitude()));
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
First check Your GPS is enabled or disabled.After enabling GPS ,using Location listener to get current location.I am using follwing code to get gps location
String sourceLat, sourceLong;
LocationManager locManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtCurrLat = (TextView) findViewById(R.id.txtCurrLat);
txtCurrLong = (TextView) findViewById(R.id.txtCurrLong);
mapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
mapView.setSatellite(false);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double fromLat = location.getLatitude();
double fromLong = roundTwoDecimals(location.getLongitude());
Toast.makeText(getApplicationContext(), fromLat +fromLong+"" , Toast.LENGTH_SHORT).show();
sourceLat = Double.toString(fromLat);
sourceLong = Double.toString(fromLong);
txtCurrLat.setText(sourceLat+","+sourceLong);
btnShow.setOnClickListener(this);
}else{
Toast.makeText(getApplicationContext(), "Location is not avilable", Toast.LENGTH_SHORT).show();
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
sourceLat = Double.toString(lat);
sourceLong = Double.toString(lng);
latLongString = sourceLat + "," + sourceLong;
} else {
latLongString = "No location found";
Toast.makeText(getApplicationContext(), latLongString+"", Toast.LENGTH_SHORT).show();
}
txtCurrLat.setText(latLongString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Disabled.Please enabale gps", Toast.LENGTH_SHORT ).show();
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
all. I am writing an android app about GPS locations.
I tried it on emulator and entered the latitude and longitude manually, and it worked fine.
However, my problem is: on the real device, in debugging mode, to go the next class by using intent can only be achieved when location is changed. If I start the app directly, I can see the blinking GPS icon, but the app will only stay here, and won't start the next activity. It seems that the variables in the onLocationChanged() will never be changed.
I have heard that to get the location instantly is to use the getLastKnownLocation() method. But I failed to get where I should use it.
Here is the class of how I use the LocationManager to get the locations.
Is there any solutions? I am quite confused. Thank you very much!!
public class mainMenu extends Activity{
private LocationManager locationManager = null;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, police.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
Button button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, ambulance.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
Button button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, fire_station.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
locationManager = (LocationManager)mainMenu.this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000 , 0, new MyLocationUpdater());
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
}
public class MyLocationUpdater implements LocationListener{ //change location interface
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// store the location data
// get the best record
Double lat = location.getLatitude();
Double lon = location.getLongitude();
System.out.println("The latitude is " + lat + "and "
+ "the longitude is "+ lon);
Double lat11 = lat - 1/69.0;
Double lat12 = lat + 1/69.0;
Double lon11 = lon - 1/42.0;
Double lon12 = lon + 1/42.0;
StaticVariables.latS1 = lat11.toString();
StaticVariables.latN1 = lat12.toString();
StaticVariables.lonW1 = lon11.toString();
StaticVariables.lonE1 = lon12.toString();
Double lat111 = lat - 2/69.0;
Double lat121 = lat + 2/69.0;
Double lon111 = lon - 2/42.0;
Double lon121 = lon + 2/42.0;
StaticVariables.latS11 = lat111.toString();
StaticVariables.latN11 = lat121.toString();
StaticVariables.lonW11 = lon111.toString();
StaticVariables.lonE11 = lon121.toString();
// ==================================================
// ambulances
Double lat21 = lat - 3/69.0;
Double lat22 = lat + 3/69.0;
Double lon21 = lon - 3/42.0;
Double lon22 = lon + 3/42.0;
StaticVariables.latS2 = lat21.toString();
StaticVariables.latN2 = lat22.toString();
StaticVariables.lonW2 = lon21.toString();
StaticVariables.lonE2 = lon22.toString();
Double lat211 = lat - 5.5/69.0;
Double lat221 = lat + 5.5/69.0;
Double lon211 = lon - 5.5/42.0;
Double lon221 = lon + 5.5/42.0;
StaticVariables.latS21 = lat211.toString();
StaticVariables.latN21 = lat221.toString();
StaticVariables.lonW21 = lon211.toString();
StaticVariables.lonE21 = lon221.toString();
// ===================================================
// fire stations
Double lat31 = lat - 2/69.0;
Double lat32 = lat + 2/69.0;
Double lon31 = lon - 2/42.0;
Double lon32 = lon + 2/42.0;
StaticVariables.latS3 = lat31.toString();
StaticVariables.latN3 = lat32.toString();
StaticVariables.lonW3 = lon31.toString();
StaticVariables.lonE3 = lon32.toString();
Double lat311 = lat - 2/69.0;
Double lat321 = lat + 2/69.0;
Double lon311 = lon - 2/42.0;
Double lon321 = lon + 2/42.0;
StaticVariables.latS31 = lat311.toString();
StaticVariables.latN31 = lat321.toString();
StaticVariables.lonW31 = lon311.toString();
StaticVariables.lonE31 = lon321.toString();
Intent intent = new Intent();
intent.setClass(mainMenu.this, getPhoneNumber.class);
mainMenu.this.startActivity(intent);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
The getLastKnownLocation method does not trigger an onLocationChanged event. One way to refactor your code would be to move the logic that acts on a Location to a separate method and then call that method both after you call getLastKnownLocation, and from your onLocationChanged method.
Bear in mind that there is no guarantee that getLastKnownLocation will provide a meaningful Location, since you the device might have moved since the last location update.
Example code:
public void onCreate(Bundle savedInstanceState){
....
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateLocation(location);
}
public class MyLocationUpdater implements LocationListener{ //change location interface
#Override
public void onLocationChanged(Location location) {
updateLocation(location);
}
...
}
void updateLocation(Location location) {
Double lat = location.getLatitude();
Double lon = location.getLongitude();
// the rest of the code from onLocationChanged
}
getLastKnownLocation() is faster after a connection has been established with the GPS satellite. For the first time, it will return null, or no value till no connection is established.
You can add a GpsListener to know when the location is obtained. Search about "how to get a gps fix" and you might get answer to your question
I have same problem before..but I have got the solution..this is the simplest way to get location instantly.
public class LocationFinder extends Activity {
TextView textView1;
Location currentLocation;
double currentLatitude,currentLongitude;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) findViewById(R.id.textView1);
Log.i("########## Inside LocationFinder onCreate", "LocationFinder onCreate");
FindLocation();
}
public void FindLocation() {
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
Toast.makeText(
LocationFinder.this,
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000)
.show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
void updateLocation(Location location) {
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
textView1.setText(String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude));
}
}
Don't forget to Give permission in Manifeast.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
public LocationManager mLocManager;
// *******This is the new Code start on 11/4/2011 at 3 o'clock
/**
* This is the Home Button if user Login then it is move to TennisAppActivity otherwise move to Login
*
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
locationUpdate();
((Button) this.findViewById(R.id.ButtonHome))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
DefaultDisplay.class));
}
});
((Button) this.findViewById(R.id.ButtonProfile))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
MyProfile.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","MyProfile");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonNotifications))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
ShowAllNotificationActiviry.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","ShowAllNotificationActiviry");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonFavorites))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (GUIStatics.boolLoginStatus) {
startActivity(new Intent(HomeActivity.this,
FavoritesActivity.class));
} else {
Intent intent=new Intent(HomeActivity.this,
Login.class);
intent.putExtra("moveTo","FavoritesActivity");
startActivity(intent);
}
}
});
((Button) this.findViewById(R.id.ButtonMore))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(HomeActivity.this,
MoreListActivity.class));
}
});
}
public void locationUpdate()
{
CellLocation.requestLocationUpdate();
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
GUIStatics.currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
GUIStatics.latitude = obj.getLatitude();
GUIStatics.longitude = obj.getLongitude();
GUIStatics.currentCity= obj.getSubAdminArea();
GUIStatics.currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
// Toast.makeText(this, "Address=>" + add,
// Toast.LENGTH_SHORT).show();
// TennisAppActivity.showDialog(add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
GUIStatics.latitude=location.getLatitude();
GUIStatics.longitude= location.getLongitude();
Log.v("Test", "IGA" + "Lat" + latitude + " Lng" + longitude);
//mLocManager.r
getAddress(latitude, longitude);
if(location!=null)
{
mLocManager.removeUpdates(this);
}
// Toast.makeText(this, "Lat" + latitude + " Lng" + longitude,
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
if(arg1 ==
LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
}
else if(arg1== LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(HomeActivity.this,
"LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
}
}
}
This is the code i have use it for finding the device location with the help of latitude and longitude and we also call getLastLocationUpdate in this code.
I hope this is very help full to you.