getLastknownLocation() returns null value on nexus - android

i am developing location based project where i am using the following code
i am using google api 8 for the project
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
currloc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
TextView t = (TextView)findViewById(R.id.textView1);
try{
t.setText("Your current location is - "+currloc.getLatitude()+","+currloc.getLongitude());
}catch (Exception e) {
// TODO: handle exception
t.setText("cant find current location ");
}
this code works fine on my galaxy tab even on htc
but when i use nexus it returns null value for location.
do i need to change my api level or is there any specific requirement for galaxy nexus
thank you in advance :)

Please follow the line of code..
Step1: into your oncreate
LocationListener locationListener = new LocalLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Step2: into class body
/**Listener on location change*/
private class LocalLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
String text = "My current Location is: "+location.getLatitude()+", "+location.getLongitude();
GeoPoint geoPoint = new GeoPoint((int)(location.getLatitude()* 1E6), (int)(location.getLatitude() * 1E6));
mapController_.animateTo(geoPoint);
Toast.makeText(LocalMap.this, text, Toast.LENGTH_SHORT).show();
Log.i("onLocationChanged", text);
}
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(LocalMap.this, "GPS Disable", Toast.LENGTH_SHORT).show();
Log.i("onProviderDisabled", "GPS Disable");
}
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(LocalMap.this, "GPS Enable", Toast.LENGTH_SHORT).show();
Log.i("onProviderEnabled", "GPS Enable");
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}

Related

how to get the position of user by GPS and if not availabe by Network

I am new in android developing, and so intrested in getting location of users!!!!!
You may know that we can access users location by two types:
GPS (ACCESS_FINE_LOCATON)
Network based (ACCESS_COARSE_LOCATION)
My Question is:
I Want to get the location(latittude & longitude) of user by GPS. But, if the user has turned GPS Off/GPS isn't supported, then i want to get user's location by Network, or, Network-based location
.
Hope you understood my question....
Any help is accepted
Try the following code:
LocationManager mlocManager;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
//if condition to check if GPS is available
if (mlocManager .isProviderEnabled(LocationManager.GPS_PROVIDER)) { mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
mlocListener, null);
}
else if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestSingleUpdate(
LocationManager.NETWORK_PROVIDER, mlocListener, null);
}
//this is the class to get the location.
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
//you may store these values where ever required.
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
When you use the FusedLocationProviderApi as used in the getting the last known location training and receiving location updates training, it will automatically fall back to network location if GPS is not available.
Hope get GPS code helps you.
if (Common.getIsGPSEnabled()) {
final LocationManager locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener;
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
myLocation = locationManager.getLastKnownLocation(locationProvider);
Toast.makeText(c, "location changed, My location is removed to"
+ myLocation.getLatitude()+","+myLocation.getLongitude(), Toast.LENGTH_LONG).show();
Latitude = myLocation.getLatitude();
Longitude = myLocation.getLongitude();
}
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);
locationManager.requestLocationUpdates(locationProvider, (long)0, (float)0, locationListener);
myLocation = locationManager.getLastKnownLocation(locationProvider);
if(myLocation != null)
{
///
}
}

general class for get current location by gps,network and not connected mode and stop after found

of course my question be duplicate. but i can not found good answer for my solution.
i want to write a custom general class that can found current location by location manager and own detect gps enabled or network enabled or use cached and stored locations when device has not gps or network enable. and above all stop work after found first location any way. but i did these works for it : 1- create two locationlistener classes(GPSListener and networkListner):
public class GPSListener implements LocationListener {
LocationManager locationManager=null;
public Boolean found=false;
public Location mainLocation=null;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
found=true;
mainLocation= location;
}
#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
}
}
public class NetworkListener implements LocationListener {
LocationManager locationManager=null;
public Boolean found=false;
public Location mainLocation=null;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
found=true;
mainLocation=location;
}
#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
}
then i use these classes in my activity same this:
LatLng result = null;
final LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (DeviceHelper.IsGPSEnabled()) {
GPSListener gpsListener = new GPSListener();
// if(gpsListener.found)
// {
if (gpsListener.mainLocation != null) {
ToastHelper.Show(this,
"GPS : " + gpsListener.mainLocation.toString());
gpsListener = null;
result = new LatLng(gpsListener.mainLocation.getLatitude(),
gpsListener.mainLocation.getLongitude());
}
// }
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
}
else if (DeviceHelper.HasConnect()) {
NetworkListener netListener = new NetworkListener();
// if(netListener.found)
// {
if (netListener.mainLocation != null) {
ToastHelper.Show(this,
"NETWORK : " + netListener.mainLocation.toString());
netListener = null;
result = new LatLng(netListener.mainLocation.getLatitude(),
netListener.mainLocation.getLongitude());
}
// }
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, netListener);
} else {
;
Location loc = LocationHelper.getLastKnownLoaction(false);
if (loc != null) {
ToastHelper.Show(this, "LAST : " + loc.toString());
result = new LatLng(loc.getLatitude(), loc.getLongitude());
}
}
if (result != null) {
LogHelper.Add("LL", String.valueOf(result.latitude));
LocationHelper.MyLatLng = result;
StaticObjects.mainMap.addMarker(new MarkerOptions().position(result));
MapHelper.CameraGo( result, 15);
} else {
LogHelper.Add("ERR:", "NULL");
}
i know this not work because manager can not found as a good time before place that i show found location. totally i want to write a general class for finding current location that can stop when found first location.
First, you don't need 2 classes for listening GPS-Glonass and Network updates. You can use just one object as a listener to both providers--since provider can be easily obtained from Location object:
if(location.getProvider().equals(LocationManager.GPS_PROVIDER)){
// it is GPS
} else if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER)){
// it is Network
}
Second, to know status of provider(s) you should implement LocationListener's onStatusChanged() callback. If a provider is unavailable at the moment you subscribe LocationListener, this callback is invoked immediately:
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (provider.equals(LocationManager.GPS_PROVIDER)
&& (status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE)){
// gps is unavailable
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)
&& (status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE)){
// network provider is unavailable
}
}
Third, to unsubscribe your object from location updates, use:
locationManager.removeUpdates(locationListener);
this will stop obtaining location updates and shut down GPS-Glonass location service if no other apps need it.

Not getting zipcode from Latitude and Longitude

I am trying to find out the latitude and longitude in an Android application. The code that I am using is as follows:-
protected int findZipCode() {
LocationManager lm = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,
1000, listener);
if (zipCode == null) {
return 0;
} else {
return Integer.parseInt(zipCode);
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
Geocoder geo = new Geocoder(getApplicationContext());
List<Address> addr = null;
try {
addr = geo.getFromLocation(location.getLatitude(),
location.getLatitude(), 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zipCode = addr.get(0).getPostalCode();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
But this code seems to always return a null value for the zipcode. Any help would be great.
Thanks in advance!!
As your MyLocationListener is running in parallel at that point your zipCode is null therefore you are getting 0 value.
Fix
You can wait the MyLocationListener to complete and pass a interface method to this listener and on the complete of this function you can call that method.
What are you doing dude?
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,1000, listener);
The above line is a asynchronus call, listener will be called when you get a position fix.
You can't check for zipcode right after this line.
In listner when you get the value of zipcode, implement some interface/callback which will give you the value of zipcode in your activity or where ever you want.

Toast doesn't disappear from screen

I have a problem with my simple android aplication that use GPS cords.
My class MyLocationListener implements LocationListener, and there is a static method call:
String strText ="My current location is: " + "Latitude = " + location.getLatitude() + " Longitude= " + location.getLongitude();
Toast.makeText(GpsModule.cont, strText, Toast.LENGTH_SHORT).show();
Problem is with displaying this string. It's showing up, and never ends. When I press back button for main menu and even when I close application it's showing up constantly. Any clue? How can I resolve this problem?
GpsModule Class:
public class GpsModule extends Activity {
public static Context cont;
//public static WebView position;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
cont = getApplicationContext();
//position = new WebView(cont);
//position = (WebView) findViewById(R.layout.gps);
//position.getSettings().setJavaScriptEnabled(true);
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
MyLocationListener class:
#SuppressLint("ShowToast")
public class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
location.getLatitude();
location.getLongitude();
String strText ="My current location is: " + "Latitude = " + location.getLatitude() + " Longitude= " + location.getLongitude();
Toast.makeText(GpsModule.cont, strText, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(GpsModule.cont, "GPS disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(GpsModule.cont, "GPS enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Please read the docs of the method LocationManager.requestLocationUpdates().
Especially the parameter:
minTime minimum time interval between location updates, in milliseconds.
Try value 10'000 for every 10 sec. In production you should consider value more than mins.
I think, you add your code in your location detection function and LocationListener is active. That means your Toast is called when GPS detect new location.
Looks like your location listener is active and repeatedly gets called. are you moving your device? LocationListener is called when the location changes.
Try this,
1 .
Toast.makeText(getBaseContext(), strText, Toast.LENGTH_SHORT).show();
2 .
#Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
3 .
#Override
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Length, long, locationListener);
}
Length and long should be more than 0.

location listner do not calling onlocation change

I am using location listener in my app.
I have the code like:
public void startlistning()
{
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
location.getLatitude();
location.getLongitude();
}
};
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
But don't know why the method onLocationChanged did not call when I restart device 1st time (without cellular data (no simcard) available). however, I am using best provider in my app.
Please look into matter. Thanks
Location listener method call when you change the location of device . Its not start when you restart device . If you want to invoke onLocationChanged method you have to change the location of device .
Please try this to get last known location.
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_FINE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera, true);
Location location = locationManager.getLastKnownLocation(providerName);
Log.i("--- Latitude",""+location.getLatitude());
Log.i("--- Latitude",""+location.getLongitude());

Categories

Resources