What is the best way to identify places on gps? - android

i'm trying to develop application with a gps that can know if i arrive at or leave a specific place.
I.E if i am at home so, the application know that and if i leaving my home the application know that too. or if i want to set the radius of my home. but i think the problem is that when i trying to running the appliction and search places every x time it could kill my battery.
what is the best solution for that action? should i using services too?
here is the class i made to get the place and the coordinates:
public class LocationMap extends Service implements LocationListener {
public static final String LOG = "locationLogger";
Context context;
LocationManager manager;
Location location;
public static final int REFRESH = 1000*1;
public static final int DISTANCE = 1*1;
double lat,lng;
boolean isGps,isWiFi;
public LocationMap(Context context) {
this.context = context;
getLocation();
}
private Location getLocation(){
try {
manager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,REFRESH,DISTANCE,this);
//Check who is on WiFi or GPS
isWiFi = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);Log.d(LOG, "Wifi?="+isWiFi);
isGps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);Log.d(LOG, "Gps?="+isGps);
Log.d(LOG, "manager is not null?="+manager);
if (manager != null) {
if(isGps){
Log.d(LOG, "get last location from Gps");
location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else
if(isWiFi){
Log.d(LOG, "get last location from WiFi");
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.d(LOG, "lat="+lat +" lng="+lng);
}
}
} catch (Exception e) {
}
return location;
}
public String getPlace(){
String placeName = "No place found, check your gps setting";
try {
Geocoder geocoder = new Geocoder(context);
List<Address> address =geocoder.getFromLocation(getLat(), getLng(), 1);
String country = address.get(0).getCountryName();
String city = address.get(0).getLocality();
String street = address.get(0).getAddressLine(0);
placeName = country+", "+city+", "+street;
} catch (IOException e) {
e.printStackTrace();
}
return placeName;
}
public double getLng(){
return lng;
}
public double getLat() {
return lat;
}
#Override
public void onLocationChanged(Location location) {
}
#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
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
sorry about my english. hope you understand me :)

That depends on your accuracy needed.
If the desired range is about 1 - 3km then there is a battery saving solution, I will not further explain here. (Using the devices Network locationg procider)
For accuracy much better there is no way around using GPS always on,
which at my iphone 4 lasts about 8 hours.
Detection if arrival is simply done via entering inside a circle, defined by lat,lon, radius.
Inside circle is calculated by:
boolean isInside = currentLocation.distanceTo(circleCenterLongitude, circleCenterLatitude) < radiusMeters.

Related

getFromLocation() returns null in Asynctask execute() method

I'm trying to make a weather app that uses Geocoder to get the current city, and then uses AsyncTask to get weather data from an api and then parse it. But when I input the current city into the AsyncTask execute() method, my app crashes:
private double latitude;
private double longitude;
String address;
LocationManager lm;
LocationListener ll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = getAddress(latitude, longitude); // getAddress() is below
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class myLocationListener implements LocationListener {
#Override
public void onLocationChanged(android.location.Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
String address = getAddress(latitude, longitude);
Task task = new Task(); // Task extends AsyncTask
task.execute(new String[] { address });
}
#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 String getAddress(double lat, double lon) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(
lat, lon, 10);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuffer str = new StringBuffer();
str.append(returnedAddress.getLocality());
str.append(",");
str.append(returnedAddress.getCountryName());
ret = str.toString();
} else {
ret = "No Address returned!";
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
I know for a fact that my getAddress() method works like it's supposed to. When I hardcode a city and state into the address field, it works like a charm. However, when I call my getAddress() method and set it to address, and then input it into execute(), the app crashes and it says that getFromLocation() returned null. Why is this happening? Is it the order of my code? Thank you for all answers in advance.
Make sure your GPS is enabled and you are not testing from the emulator. The provider will return null if it is not enabled as per the documentation. Since you need the current location and probably you do not want updates I will recommend you use requestSingleUpdate(). A better option will be to use the new LocationClient Class that is part of Google Services; its fused provider gets the best Location available for you.

not getting location using gps in android

I'm trying sample code for getting location using gps service.bt not gettong location.
Below is my code.-
public class MainActivity extends Activity implements LocationListener{
Location mLocation;
LocationManager mManager;
LocationListener mlistener;
Geocoder mcoder;
Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
txtLat = (TextView) findViewById(R.id.tv);
}
public void getMyLocation(){
String addressString = "";
final Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
final List<Address> addresses = gc.getFromLocation(18.5203, 73.8567, 4);
final StringBuilder sb = new StringBuilder();
System.out.println("location..."+sb);
if ( addresses.size() > 0 )
{
final Address address = addresses.get(0);
for ( int i = 0; i < address.getMaxAddressLineIndex(); i++ )
{
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch ( final IOException e )
{
}
txtLat.setText("Your Current Position is:\n" +
"\n" + addressString);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
getMyLocation();
}
#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
}
}
Your code just needs some minor changes.
You must implement all methods of the listener to understand if the provider is available, if any is built into the device and if you can expect Location updates anyway.
In getMyLocation() you call the Geocoder.getFromLocation() with hardcoded latitude and longitude. Is this for debugging purposes?
Then there's a System.println() of a newly created , empty StringBuilder. If you want to print something out it's better to use Log.d().
And finally - if everything else works, but you still get no address in the textview - then try to Toast the address. It has less possibilities to go wrong but you need to stare on the screen as the message disappears after a second.
My guess here is, that your Emulator has no GPS configured or you do not get updates - either because there's no satellite or you simply do not wait long enough for satellite connections.

Android GPS is returning outdated info

In my current application, the location data that is returned is outdated. I use a method that gets updates based on min time/distance between updates. However, lets say i turn my phone off, drive to another city, and then turn the phone back on. In this case my GPS reading will be off. How do i force the app to get the current location NOT getLastKnownLocation().
I have heard of a locationListener but everything i have read is very vague on how to use it.
Here is the code I have just in case this clarifies whats going on:
public class GPSHandling extends Service implements LocationListener{
private final Context myContext;
//flag for gps status
public boolean isGPSEnabled = false;
//flag for network status
public boolean isNetworkEnabled = false;
// used to determine if i can get a location either by network or GPS
public boolean canGetLocation = false;
Location myloc;
public double latitude;
public double longitude;
public int MIN_TIME_BTWN_UPDATE = 500*10; // in miliseconds, so 10sec
public int MIN_DISTANCE_BTWN_UPDATE = 10; // in meters
protected LocationManager locManager;
public GPSHandling(Context context){
this.myContext= context;
getLocation();
}
public Location getLocation(){
try{
locManager =(LocationManager) myContext.getSystemService(LOCATION_SERVICE);
// now get gps status
isGPSEnabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//now the same for network
isNetworkEnabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled){
// do nothing since neither provider are enabled (this.cangetlocation = false but its already set to that by default)
}
else{
this.canGetLocation=true;
//first get values for locManager from the network provider. send parameters telling when to update
if(isNetworkEnabled){
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BTWN_UPDATE, MIN_DISTANCE_BTWN_UPDATE, this);
Log.d("provider", "network");
//if we are successful, then check to see if the location manager isnt null. attempt to get the current location from the manager
if (locManager != null){
myloc =locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// after getting the current location, attempt to get the latitude and longitude values
if (myloc != null){
latitude = myloc.getLatitude();
longitude = myloc.getLongitude();
}
}
}
//now get values for locManager from the GPS provider. send parameters telling when to update
if(isGPSEnabled){
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BTWN_UPDATE, MIN_DISTANCE_BTWN_UPDATE, this);
Log.d("provider", "GPS");
}
//if we are successful, then check to see if the location manager isnt null. attempt to get the current location from the manager
if(locManager!= null){
myloc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// after getting the current location, attempt to get the latitude and longitude values
if(myloc != null){
latitude = myloc.getLatitude();
longitude = myloc.getLongitude();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return myloc;
}
// get an update of the current latitude by using this class method
public double getMyLatitude(){
if (myloc!= null){
latitude = myloc.getLatitude();
}
return latitude;
}
//get an update of the current longitude by using this class method
public double getMyLongitude(){
if (myloc != null ){
longitude = myloc.getLongitude();
}
return longitude;
}
// use this method to find if app can get the current location
public boolean canGetMyLocation(){
return this.canGetLocation;
}
public void showGPSDialog(){
AlertDialog.Builder alert = new AlertDialog.Builder(myContext);
// Setting Dialog Title
alert.setTitle("Location Setting");
// Setting Dialog Message
alert.setMessage("GPS is not enabled, do you want to enable this now in the settins menue?");
// setting icon to dialog
//alert.setIcon(R.drawable.)
// on pressing settings button
alert.setPositiveButton("Settins", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
myContext.startActivity(intent);
}
});
//on pressing cancel button
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// showing the alert dialog
alert.show();
}
public void stopUsingGPS(){
if(locManager !=null){
locManager.removeUpdates(GPSHandling.this);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You are already half using LocationListener in your code. You just didn't fully implement the code.
This method bellow is empty in your code:
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
This is the method that is called everytime GPS produces an location update.
You should complete it doing something like:
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
Regards.
Did you read the corresponding docs?
Look at Location API and LocationListener for the start.
LocationListener is actually pretty straight-forward to use and the only (clean) way to reliably retrieve the device's location.
Location data usually take up to 30 seconds to fully warm up. As you asked for the getLastKnownLocation() you, indeed, could have a outdated location returned.
Read more about it at Location strategies by Google itself.

Find out the speed of the User in android Using GPS

I tried to find out the speed of User, while user is moving with device. Here, I followed one link with sample code. i.e: Here SpeedDemo.
The problem is, by using location.getSpeed() method, we are finding the speed. So, for that I changed the location values in device, but every time the value of the location.getspeed() return '0' only. Why it happen, even changing the location itself.
Can any one known about this?
You have to track location Updates, and when the method onLocationChanged(Location location) triggers, you can call location.getSpeed(); it will give you correct speed, if your phone is actually moving.
But if you are testing it on Simulator, and sending location by emulator controller, it will always return 0.
Updated with Example
public class LocationService implements LocationListener {
LocationService locationService;
LocationManager locationManager;
Location lastLocation;
private final String TAG = "LocationService" ;
private final String MOCK_LOCAION_PROVIDER = "FAKE_PROVIDER";
LocationService(Context ctx) {
LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
String mocLocationProvider = MOCK_LOCAION_PROVIDER;
if (locationManager.getProvider(mocLocationProvider) != null) {
locationManager.removeTestProvider(mocLocationProvider);
}
locationManager.addTestProvider(mocLocationProvider, false, false, false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
locationManager.requestLocationUpdates(mocLocationProvider, 0, 0,
this);
try {
List<String> data = new ArrayList<String>();
InputStream is = ctx.getAssets().open("data.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
data.add(line);
}
// Log.e(TAG, data.size() + " lines");
new MockLocationProvider(locationManager, mocLocationProvider, data).start();
} catch (IOException e) {
e.printStackTrace();
}
}
class MockLocationProvider extends Thread {
private List<String> data;
private LocationManager locationManager;
private String mocLocationProvider;
private String LOG_TAG = "MockLocationProvider";
public MockLocationProvider(LocationManager locationManager, String mocLocationProvider, List<String> data) throws IOException {
this.locationManager = locationManager;
this.mocLocationProvider = mocLocationProvider;
this.data = data;
}
#Override
public void run() {
for (String str : data) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Set one position
String[] parts = str.split(",");
Double latitude = Double.valueOf(parts[0]);
Double longitude = Double.valueOf(parts[1]);
float speed = Float.valueOf(parts[2]);
Location location = new Location(mocLocationProvider);
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setSpeed(speed);
// location.setAltitude(altitude);
// Log.d(LOG_TAG, location.toString());
// set the time in the location. If the time on this location
// matches the time on the one in the previous set call, it will
// be
// ignored
location.setTime(System.currentTimeMillis());
locationManager.setTestProviderLocation(mocLocationProvider, location);
}
}
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e(TAG, "onLocationChanged");
// Get Location Speed Here
Log.d(TAG, "Speed " +location.getSpeed());
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
// Log.e(TAG, "onProviderDisabled : "+provider);
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
// Log.e(TAG, "onProviderEnabled : "+provider);
}
public void onStatusChanged(String provider, int status, Bundle arg2) {
// TODO Auto-generated method stub
// Log.e(TAG, "onStatusChanged : "+status);
}
}
The Above code is actually a location service class, when you make an instance of this class, it register a fake Location Service(other than GPS, and Network) provider, and input some fake location parameters by a given file.
Below is the data.txt file which has latitude,longitude,speed the above class read this data.txt file and input fake lat,lon, and speed in the location, as well as trigger time to change location is also implemented by Thread.sleep() call.
Data.txt file
24.856449265609735,67.04308920288086,1.64
24.856749265609735,67.04408920288086,7.64
24.856949265609735,67.04508920288086,11.64
24.857649265609735,67.04716920288086,13.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.1
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.857849265609735,67.04729920288086,17.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04739920288086,16.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.1
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.857849265609735,67.04729920288086,17.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04739920288086,16.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.1
24.857849265609735,67.04729920288086,17.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04739920288086,16.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
I think getSpeed() will work only if the particular location have speed component available with GPS. Otherwise it will returned 0.0 all the time.
For that you can check that using condition location.hasSpeed() method. If true then do your stuff else think another way.
First we need to check whether the Gps Enabled or not using location manager.
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Then , you need to implement GpsStatus.Listener to get the Gps updates. It will return the Gps location updates.
GPSManager.locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
if (GPSManager.gpsCallback != null) {
GPSManager.gpsCallback.onGPSUpdate(location);
}
}
#Override
public void onProviderDisabled(final String provider) {
}
#Override
public void onProviderEnabled(final String provider) {
}
#Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
};
From that location you can able to get the current speed.
speed = location.getSpeed();
Refer to my website here for further details : http://velmm.com/get-current-user-speed-using-gps-android/

Android Location can not be entered to edit texts

I wrote a program to show my current location, Address etc in android phone. The API used is Android 2.2. Previously it worked fine in a MTS CDMA phone. It had an API of Android 2.3. It also works fine in emulator. Now. I have bought a Sony Ericsson Xperia Minipro and it also has Android 2.3. But the program will run on it. But the edit texts will not show anything. I use edit texts to display the values. They are not updated by the program at all. What can be the problem? Same program works fine in emulator and it shows location! Please help. I can paste the code below
public class TravelGuide extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES=1;
private static final long MINIMUM_TIME_BETWEEN_UPDATES=1000;
StringBuilder strReturnedAddress;
List<Address> addresses;
protected LocationManager locationManager;
static String videoId;
Double lat;
Double longd;
Address returnedAddress;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//Double latitude = location.getLatitude();
//Double longitude = location.getLongitude();
}
#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
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,new MyLocationListener());
showCurrentLocation();
}
public void showCurrentLocation()
{
Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null)
{
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
String message=String.format("currentLocation\n Longitude:%1$s \n Latitude:%2$s",location.getLongitude(),location.getLatitude());
Toast.makeText(TravelGuide.this,message,Toast.LENGTH_LONG).show();
myLatitude.setText("Latitude: " + String.valueOf(location.getLatitude()));
myLongitude.setText("Longitude: " + String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.valueOf(location.getLatitude()),
Double.valueOf(location.getLongitude()), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
videoId = (returnedAddress.getAddressLine(1)).toString();
//sendAddress(videoId);
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//test = "kovalam";
myAddress.setText("Canont get Address!");
}
}
}
public class MyLocationListener implements LocationListener
{
//private final Context MyLocationListener = null;
//double LATITUDE;
//double LONGITUDE;
TextView myLatitude;
TextView myLongitude;
TextView myAddress;
public void onLocationChanged(Location location)
{
//Context context = null;
myLatitude = (TextView)findViewById(R.id.mylatitude);
myLongitude = (TextView)findViewById(R.id.mylongitude);
myAddress = (TextView)findViewById(R.id.myaddress);
//String message=String.format("new Location\n Longitude:%1$s \n Latitude:%2$s",
//location.getLongitude(),location.getLatitude());
//Toast.makeText(TouristGuideActivity.this,message,Toast.LENGTH_LONG).show();
myLatitude.setText("Latitude: " + String.valueOf(location.getLatitude()));
myLongitude.setText("Longitude: " + String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(TravelGuide.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.valueOf(location.getLatitude()),
Double.valueOf(location.getLongitude()), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
videoId = (returnedAddress.getAddressLine(1)).toString();
//sendAddress(videoId);
//myAddress.setText(strReturnedAddress.toString());
myAddress.setText("Hello");
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
}
public void onStatusChanged(String s, int i, Bundle b)
{
//Toast.makeText(TouristGuideActivity.this,"Provider status changed",Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s)
{
Toast.makeText(TravelGuide.this,"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s)
{
Toast.makeText(TravelGuide.this,"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
you are getting locaton object null,try put log in else condition..and the reason is you are fetching last known location which in not available in that phone some how..
so if its true..
Go to this answer here implement that code to get current location...and it will work fine.
If you are using GPS Provider to get Location,Its found that Its not so accurate to return you location object,Network Provider is better option According to me.

Categories

Resources