getFromLocation() returns null in Asynctask execute() method - android

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.

Related

What is the best way to identify places on gps?

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.

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.

adding AsyncTask for searching location

so I am making an application to get current position. The code below is working fine
String stringAddress = "";
public void getLocation(View view){
final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria kriteria = new Criteria();
kriteria.setAccuracy(Criteria.ACCURACY_FINE);
kriteria.setAltitudeRequired(false);
kriteria.setBearingRequired(false);
kriteria.setCostAllowed(true);
kriteria.setPowerRequirement(Criteria.POWER_LOW);
final String provider = lm.getBestProvider(kriteria, true);
final Location lokasi = lm.getLastKnownLocation(provider);
updateWithNewLocation(lokasi);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, ll);
edittext_position.setText(stringAddress);
}
private void updateWithNewLocation(Location
if(lokasi != null){
double lat = lokasi.getLatitude();
double lng = lokasi.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try{
List addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if(addresses.size()>0){
Address address = addresses.get(0);
sb.append(address.getAddressLine(0));
stringAddress= sb.toString();
}
} catch (Exception e){
}
}
}
private final LocationListener ll = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
}
but the problem is everytime I call getLocation() function, the application hang for a couple second before returning the result. I know to solve this problem using aSyncTask but I don't know how to start. Appreciate your help.
Thank you
It's snippet from my application:
public void getCurrentLocation(final ListenerGetCurrentLocation listenerGetCurrentLocation) {
new AsyncTask<Void, Void, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... voids) {
Geocoder geo = new Geocoder(instance);
List<Address> listAddresses = null;
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
if (location != null) {
listAddresses = geo.getFromLocation(location.getLatitude(),
location.getLongitude(),
1);
}
} catch (IOException e) {
e.printStackTrace();
}
return listAddresses;
}
public void onPostExecute(List<Address> listAddresses) {
Address _address = null;
if ((listAddresses != null) && (listAddresses.size() > 0)) {
_address = listAddresses.get(0);
GeoPoint currentPosition = new GeoPoint(((int)(_address.getLatitude() * 1E6)),
((int)(_address.getLongitude() * 1E6)));
}
}
}.execute();
}
requestLocationUpdates() is asynchronous, it doesn't block your app. It polls the location in the background, then it calls the listener.
However, gc.getFromLocation() is not. This is probably the cause of your lag
Create a new AsyncTask, Eclipse will propose you to override those methods
#Override
protected List<String> doInBackground(String... params) {
// this is done in the background so it won't block the UI. The return type must be set to List<String> (I think default is just String)
return gc.getFromLocation()
}
#Override
protected void onPostExecute(List<String> adresses) {
// called when the GC work is finished. You can now use your list of addresses and display them
}
Don't forget to call execute() on your task.

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.

reverse geocoding not working

i written following code to get current location. although I m testing it in emulator with different latitude and longitude. But it cant convert the lattitude and longitude in real location.
public class LocationFindingActivity extends Activity {
/** Called when the activity is first created. */
EditText et;
LocationManager locationManager;
String provider;
LocationListener locationListener;
Location currentLocation;
String addressString="";
String longlattString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.locationTXT);
locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
currentLocation=locationManager.getLastKnownLocation(provider);
et.setText(addressString);
locationListener =new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updateWithNewLocation(currentLocation);
}
};
updateWithNewLocation(currentLocation);
locationManager.requestLocationUpdates(provider, 2000, 10,locationListener)
}
private void updateWithNewLocation(Location location) {
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
longlattstring="Lattitude :"+lat+"Longitude :"+lng;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
//Toast.makeText(this, "Problem1", 2000).show();
if (addresses.size() > 0)
{
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");
Toast.makeText(this, "Problem2", 2000).show();
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (IOException e)
{
Toast.makeText(this, "Problem Catch", 2000).show();
}
}
else
{
addressString = "No location found";
}
et.setText(addressString);
}
}
I am getting problem in this line
List addresses = gc.getFromLocation(lat, lng, 1);
the statement doesn't return anything.
It's a known bug which they never fixed see service not avavilable.I think you will find that it works in the the API level 7 emulator.

Categories

Resources