I've got a problem when I try to find my current location that I need to display the weather. This is the method I use to find my location:
protected class GetPosition extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
List<Address> addresses = null;
try {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
addresses = gcd.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) return addresses.get(0).getLocality();
} catch (Exception e) {
return "Nessuna posizione disponibile";
}
return addresses.get(0).getLocality();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
citylb.setText(s);
getWeather((String) citylb.getText());
}
}
and this is the way I check if there is some connection like data or wifi:
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null || netInfo.isConnectedOrConnecting()) { //Here crashes
return true;
}
return false;
}
private void getWeather(String location) {
if (isOnline()) {
Log.d("YWeatherGetter4a", "onCreate");
YahooWeatherUtils yahooWeatherUtils = YahooWeatherUtils.getInstance();
yahooWeatherUtils.queryYahooWeather(getApplicationContext(), location, this);
} else
Toast.makeText(getApplicationContext(), "Sorry, no connection available", Toast.LENGTH_SHORT).show();
}
I've got two problems:
1) If I am without any connection, the application crashes at the line if (netInfo != null || netInfo.isConnectedOrConnecting())
, netInfo seems null
.
2) The location isn't always correct. Frequently it returns an "old" location and not current. Example: if two hours ago, I was at Rome and now in Milano, it shows me Rome. I can't understand where I'm wrong.
About first problem I tried also writing: if (netInfo != null && netInfo.isConnectedOrConnecting())
with the &&
instead ||
. Not crashes but it finds the location only in wifi and not in data connection. How can I solve these problems? Thanks