In the code below getLastKnownLocation() always returns null on a device, even when I am getting Provide = internet. It was working fine but know it's returning a null value. I am using a Galaxy Tab version 2.2.
public void find_Location(Context con) {
Log.d("Find Location", "in find_location");
this.con=con;
String location_context = Context.LOCATION_SERVICE;
LocationManager locationManager =
(LocationManager)con.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status,Bundle extras){}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Geocoder geocoder = new Geocoder(AdvanceSearch.this,
Locale.getDefault());List<Address> addresses;
try {
addresses = geocoder.getFromLocation(lat,lng,100);
countryname=addresses.get(0).getCountryName();
eexit e = new eexit();
statename= addresses.get(0).getAdminArea();
cityname=addresses.get(0).getLocality();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Thanks in advance for your help.
I would focus on this line first. Your requestLocationUpdates has a minDistance set at 0.
Play around with the minDistance, I think that is where your problem is.
locationManager.requestLocationUpdates(provider, 1000, 15, new LocationListener() {
Edit:
In addition I would add a Log to your LocationListener methods. Doing this has helped me quite a bit.
Here is an example of my early LocationListener script:
public LocationListener jLocListener = new LocationListener() {
//class findMe implements LocationListener {
public void onLocationChanged(Location location) {
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (Exception e) {
Log.e("onLocationChanged", "FAILED: " + e.getMessage());
}
}
public void onProviderDisabled(String provider) {
Log.i("LocationListener", "onProviderDisabled");
}
public void onProviderEnabled(String provider) {
Log.i("LocationListener", "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("LocationListener", "onStatusChanged");
}
Related
So I am getting the longitude and latitude as:
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude=location.getLongitude();
latitude=location.getLatitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Or use LocationManager.GPS_PROVIDER
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation!=null){
longitude=lastKnownLocation.getLongitude();
latitude=lastKnownLocation.getLatitude();
}
then I am getting my location depending on these info:
Geocoder myLocation = new Geocoder(Time.this, Locale.getDefault());
List<Address> myList=null;
try {
myList = myLocation.getFromLocation(latitude,longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(myList != null && myList.size()>0) {
address= (Address) myList.get(0);
if(address.getAddressLine(0)!=null){
addressStr += address.getAddressLine(0);
}
if(address.getAddressLine(1)!=null){
addressStr += ", "+address.getAddressLine(1);
}
if(address.getAddressLine(2)!=null){
addressStr += ", " +address.getAddressLine(2);
}
}
But sometimes the location stays null until I restart my phone why that's happening? and is there a way to fix it?
Try to setup your Location Listener as below :
public class BasicMapActivity_new2 extends Activity implements
LocationListener {
private LocationManager locationManager;
private String provider;
Double Latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new2.this, "GPS signal not found",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else if (!enabledWiFi) {
Toast.makeText(BasicMapActivity_new2.this,
"Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
// do something
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// Toast.makeText(BasicMapActivity_new.this, "Location " + lat+","+lng,
// Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Latitude = lat;
longitude = lng;
Toast.makeText(BasicMapActivity_new2.this,
"Location " + coordinate.latitude + "," + coordinate.longitude,
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
And do not forget to add permission into manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Update: This is because to add requestLocationUpdates() into onResume() and removeUpdates(this); into onPause(). This way your app will stop updated locations when it is not active. add below into your Activity:
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
this is a documented issue in google forums. Check this thread:
https://code.google.com/p/android/issues/detail?id=57707
Also i think the solution for this is to use Google Location API, this requires that you have Google Play services up to date and >= 2.2 i think. Hope this helps you. I battled this issue for long
I have this error .
02-13 15:13:18.110: E/AndroidRuntime(2256): java.lang.RuntimeException: Unable to start activity ComponentInfo{scom.example.sampol/scom.example.sampol.MainActivity}: java.lang.NullPointerException
this is my code . on getting location
public void onclickLocation(View v){
txt1=(TextView) findViewById(R.id.textLocation);
/* Use the LocationManager class to obtain GPS locations */
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
addresses = gcd.getFromLocation(loc.getLatitude(),loc.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text=(addresses!=null)?"City : "+addresses.get(0).getSubLocality()+"\n Country : "+addresses.get(0).getCountryName():"Unknown Location";
String textVal = "My current location is: "+ text;
txt1.setText(textVal);
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
Have you add this Permission in Your Manifest xml?
Of Access Course Location And Access Fine Location in Manifest
I'm able to get location update from network provider but when it comes to gps it takes a lot of time for the data to be picked. I want to keep a particular time for which only the GPS listener will work and then move on to network provider after sometime. How to fix this issue ?
This is my code..
public void gpslocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
networklocation();
}
};
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 10 * 1000, (float) 10.0,locationListener);
}
public void networklocation()
{
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
updateLocationForGeo(location);
//update(location);
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
System.out.println(provider+ "enabled provider");
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println(provider+ "disabled provider");
isGpsProvidersDisabled=true;
}
};
String timeProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(timeProvider, 1 * 1000, (float) 10.0, locationListener);
}
public void updateLocationForGeo(Location location){
System.out.println("location updated");
double dev_lat = location.getLatitude();
double dev_lang = location.getLongitude();
boolean out_of_range=false;
for(int i=0; i<arrayLength; i++){
double lattDiff = Math.toRadians(latarr[i]-dev_lat);
double longDiff = Math.toRadians(lonarr[i]-dev_lang);
double distance=(Math.sin(lattDiff/2)*Math.sin(lattDiff/2))+(Math.sin(longDiff/2)*Math.sin(longDiff/2)*Math.cos( Math.toRadians(latarr[i]))*Math.cos( Math.toRadians(dev_lat)));
System.out.println(distance+" distance" );
double c= (2 * Math.atan2(Math.sqrt(distance), Math.sqrt(1-distance)));
double radius=radarr[i]* 1.60934;
double d = 6371 * c;
if(d>radius)
{
out_of_range=true;
continue;
}
else{
System.out.println("enjoy");
out_of_range=false;
break;
}
}
Any help would be greatly appreciated.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
public class MyLocationListener implements LocationListener {
private Address mAddresses;
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
mAddresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e) {
}
String cityName = (mAddresses != null) ? mAddresses.get(0)
.getLocality() : TimeZone.getDefault().getID();
String countryName = (mAddresses != null) ? mAddresses.get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
mCurrentSpeed.setText("Longitude"+loc.getLongitude()+" Latitude"+loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
I am making an app in which i have to get latitude and longitude of device and my code is as follows:
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600, 0, mlocListener);
System.out.println("mlocManager"+mlocManager);
String str = latitude + "," + longitude ;
System.out.println("latitude"+latitude);
System.out.println("longi:"+longitude);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
try
{
System.out.println("............ ..............................Location changedin 11");
latitude = loc.getLatitude();
longitude = loc.getLongitude();
// System.out.println("latitude"+curr_lat);
System.out.println("longitude curr_lon");
loc.getAccuracy();
}
catch (Exception e1) {
e1.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
But at the end i am getting lat and long as 0.0 . Can anyone help me.
Add the following permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
You should give some time to get location info like 10sec,20sec etc.For this you can use timer.
I have given an example.You can Implement like this.
private Location getCurrentLocation(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) 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.
t.cancel();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
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);
Location lastKnownLocation;
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
this.cancel();
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
return lastKnownLocation;
}
},30000);
}
I want to develope an app in which when i start the app it will first give me Latitude and Longitude of my current location. Here is my code:
LocationListener locLis=new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onLocationChanged(Location location)
{
// TODO Auto-generated method stub
Double lat=location.getLatitude();
Double lon=location.getLongitude();
Log.i("Latitude=="+lat,"=="+lon);
}
};
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,0,0, locLis);
I use ACCESS_FINE_LOCATION in the manifest file.
But when i start the app there is no latitude and longitude it found. Why? If i change the location's latitude longitude from the command prompt then it will show the updated latitude and longitude. Please anyone help me
Take this code and enjoy
public void find_Location(Context con)
{
Log.d("Find Location", "in find_location");
this.con=con;
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)con.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers)
{
locationManager.requestLocationUpdates(provider, 1000, 0,new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status,Bundle extras){}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
addr=ConvertPointToLocation(latitude,longitude);
String temp_c=SendToUrl(addr);
}
}
}
public String ConvertPointToLocation(double pointlat,double pointlog) {
String address = "";
Geocoder geoCoder = new Geocoder(con,
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(pointlat,pointlog, 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();
}
return address;
}
Your code is set to display the location only when it changes.
I think in order to display it when the app starts, you should try putting it in onProviderEnabled() or some other initialization routine.
You should do like this
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{}
#Override
public void onProviderDisabled(String provider)
{}
#Override
public void onProviderEnabled(String provider)
{}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);