In my project I'm trying to get the latitude, the longitude and the address but for some reason I can't get it appears the message Location not available everytime.
In the manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Have someone had this issue before?
This is my class:
public class GEO extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geo);
latituteField = (TextView) findViewById(R.id.txt1);
longitudeField = (TextView) findViewById(R.id.txt2);
addressField = (TextView) findViewById(R.id.txt3);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Log.d("SomeTag", provider);
Log.d("SomeTag", String.valueOf(locationManager.isProviderEnabled(provider)));
Location location = locationManager.getLastKnownLocation(provider);
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if (lastKnownLocation != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(lastKnownLocation);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
addressField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {}
catch (NullPointerException e) {}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
I do run my project with a phone
It could be that address.get(0) is null in
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
And you are catching the NPEs, so it might be difficult to identify exactly why you are not getting the expected results.
Something like this might help:
try {
List<Address> addresses = geoCoder.getFromLocation(lat, lng, 1);
Address firstAddress = addresses.get(0);
if(firstAddress != null) {
int maxLines = firstAddress.getMaxAddressLineIndex();
for (int i = 0; i < maxLines; i++) {
String addressStr = firstAddress.getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
addressField.setText(builder.toString()); //This will display the final address.
}
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} catch (IOException e) {
e.printStackTrace();
}
Also, from http://developer.android.com/reference/android/location/Geocoder.html
Try checking isPresent
public static boolean isPresent ()
Added in API level 9
Returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented. Lack of network connectivity may still cause these methods to return null or empty lists.
Related
I need to fetch locations or addresses of nearest location of a current gps location to show on google map.Currently i am able to show some locaions on map but that are hardcoded i need to fetch all nearest location before drawing the map.
Is there any suggestion?
Here is the way, that how can you achieve it.
LocationManager locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = 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) {
Double l1 = location.getLatitude();
Double l2 = location.getLongitude();
address = GetAddress(l1, l2);
}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
private String GetAddress(Double lat, Double lon) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
String ret = "";
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
if (!addresses.equals(null)) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("\n");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress
.append(returnedAddress.getAddressLine(i)).append(
"\n");
}
ret = "Around: " + strReturnedAddress.toString();
} else {
ret = "No Address returned!";
}
} catch (IOException e) {
e.printStackTrace();
ret = "Location: https://maps.google.co.in/maps?hl=en&q=" + lat
+ "," + lon;
} catch (NullPointerException e) {
e.printStackTrace();
ret = lat + "," + lon;
}
return ret;
}
And also add these permissions in AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
First get your current location Lattitude & Longitude, then get Lattitude & Longitude of each locations you have and find out distance of each place from your current location using distanceTo method of Location class and after that find out least distance from your list.
i need your help regarding the location update in android. Following is my code for getting location update and it is working fine. But it returns invalid message body when i get the stored variable with location in oncreate method of main class. After thorough research it seems that the variable i called in oncreate method is empty. Can you please tell me how to get the address as it appears in onlocationChanged Method. Thank you!
Calling class with oncreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
String address1= listener.getAddress();
{
sendSms(phone, message, false);
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
location class:
class Mylocation implements LocationListener{
double lat, lon;
static final String address="";
public void onLocationChanged(Location location)
{
//...
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address); //working here
}
public String getAddress(){ //not returning the address
return address;
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Make sure your variables are initialized properly. I don't see evidence of this in the question so I am just checking.
// Instantiation
Mylocation listener;
String phone;
String message;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
listener = new Mylocation(this);
phone = "";
message = "";
// These two lines aren't really necessary,
// this should be in your MyLocation class
//locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
// Add this line, we are going to initialize this class
// and make sure that address gets set
listener = new Mylocation();
String address1 = listener.getAddress();
try {
// If neither phone nor message is empty lets sendSms()
if (!phone.isEmpty() || !message.isEmpty()) {
sendSms(phone, message, false);
}
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
Change the String address to private and in the getter try return this.address;
class Mylocation implements LocationListener {
double lat, lon;
// Let's make this private so it can't be accessed directly,
// since you have the setter and getter.
private String address = "";
// Make sure you are overriding this method
#Override
public void onLocationChanged(Location location) {
/** ... */
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address);
}
public String getAddress(){
return (address.isEmpty()) ? "Address not set" : this.address;
}
public String GetAddressDetail(Double lat2, Double lon2) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Edit
I made changes to your code in my answer above, check the comments. I am also going to suggest additional methods for your MyLocation class:
class Mylocation implements LocationListener {
protected LocationManager locationManager;
private Context activityContext;
// The initializing method, this fires off first
// when a new instance of the class is created
public MyLocation(Context context) {
this.activityContext = context;
locationManager = (LocationManager) activityContext.getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);) {
locationManager.requestLocationUpdates(
NETWORK_PROVIDER,
MIN_TIME,
MIN_DISTANCE,
this
);
}
getLocation();
}
private double lat;
private double lon;
public double getLat() {
return this.lat;
}
public double getLng() {
return this.lng;
}
public void getLocation() {
if (location == null) {
locationManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);
if (location != null) {
// Set the coordinate variables
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("Network", "Lat: " + latitude + " / Lng: " + longitude);
}
}
}
}
}
You are calling getAdress directly after you set the locationmanager to probe for a location. The onLocationChanged method probably hasn't been called yet when you call getAddress this way. I would recommend changing it to something like below to make sure it has been called:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//...
long lat = location.getLatitude();
long lon = location.getLongitude();
String address = GetAddressDetail(lat, lon);
//Do whatever you want to do with the address here, maybe add them to the message or something like that.
sendSms(phone, message, false);
}
});
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
I'm working on GPS based application that gets the address based on GPS provider but sometimes it doesn't work due to lack of signal like as at underground parking or similar places. So in such situtation i want to take the address through Network provider and send SMS via sendSMS() method. It has to repeat every 10 mints and call the sendSMS() method with updated Location.
The code for getting GPS location is below could you please suggest me to edit it according to my need?
public class WPGActivity extends Activity {
ImageButton start;
Button login;
String ADDRESS, LOCATION;
TextView addressText, locationText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(ImageButton)findViewById(R.id.imageButton1);
login=(Button)findViewById(R.id.button1);
addressText = (TextView)findViewById(R.id.addressText);
locationText = (TextView)findViewById(R.id.locationText);
myLocation();
// if(ACTIVE_MODE==1) startApp();
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getAddress(); // to get address
sendSMS(); // to send sms
sendEmail(); // to send email
}
});
}
public void myLocation(){
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 30, locationListener);
}
public void getAddress(){
try{
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
if (addresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < addresses.size(); i++){
Address address = addresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
result.append(",");
}
result.append(address.getLocality());
result.append(",");
result.append(address.getPostalCode());
result.append("\n\n");
}
ADDRESS = result.toString();
addressText.setText(ADDRESS);
}
}
catch(IOException ex){
ADDRESS= ex.getMessage().toString();
addressText.setText(ADDRESS);
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
locationText.setText(LOCATION);
}
}
I have written code in that if GPS is disabled it will be enabled by code and try to get Location from gps but I am getting a null value. Below is my code
public void getValue() {
LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
System.out.println("GPS IS "+gpsEnabled);
if (!gpsEnabled) {
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
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);
}
}
SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
try {
getBatteryLevel();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocation = location;
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
address = getAddress();
alt = location.getAltitude();
if (meterFootFlag) {
diameter = location.getAccuracy();
} else
diameter = location.getAccuracy() / 3.28084;
} else {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
} catch (Exception e) {
lat = 0.0;
lon = 0.0;
alt = 0.0;
}
Also I have added permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
but I am getting a null value for the location.
Any ideas on how I can get the location?
Your code is correct just wait until GPs get altitude from a satellite it may take mroe than 1 minute.
try:
public Location showLocation(){
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Class model, save latitude and longitude
NavegadorCoordenadas locate = new NavegadorCoordenadas();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, false);
Location loc = getLastKnownLocation(lm);
locate.setLatitude(loc.getLatitude());
locate.setLongitude(loc.getLongitude());
return loc;
}
private Location getLastKnownLocation(LocationManager location) {
List<String> providers = location.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = location.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Make sure that you are checking on DEVICE only.. In Emulator it will give Null Values for GPS as it is running in the system so it doesnot have permission for GPS
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
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);
}
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
locationListener);
Now make MyLocationListener class in same activity.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " +loc.getLongitude();
String latitude = "Latitude: " +loc.getLatitude();
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
System.out.println("MESSAGE:"+cityName);
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude+"\t city name:"+cityName;
Log.v("OUTPUT, s);
}
#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
}
}
Run your application in Actual device.
you can figure out that automatic start GPS and see console logcat.
Make sure to open Permissions through the
Settings--> Applications-->YourApp-->permissions
And another reason could be delay, it takes time to connect to network, somethimes more than a minute
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
} );}