Execute async method inside onLocationChanged() - java

I have a class which extends from AsyncTask and gets data in JSON format from a web service. My android app has to retrieve data asynchronously whenever the location is changed. My android activity implements LocationListener and I am invoking the asynchronous execution in onLocationChanged() method. I have tried setting zero for both minTime and minDistance parameters of requestLocationUpdates() method but the data which is to be retrieved asynchronously is never retrieved.
The code for my onCreate() and onLocationChanged() methods is given below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
}
#Override
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLatitude());
new MyAsyncTask().execute();
}
The latitude and longitude variables are used in the MyAsyncTask class for getting data with respect to user's current location.
Please tell me what's wrong with my code. I have been looking for the solution since last week but haven't found any.

oke, a little bit confused but let me understand it. You retrieve the data in onLocationChanged() ? example long=111 lat=222 and with your Asyntask you make a GET request to a WS with a json parameter probably long and lat and some other stuff in it ? and if you try to debugg it there are some values in logcat ? or some error ? or did you put the permision in the manifest file ? or in the phones settings ?

did tried debugging??
or
Log??
are you getting any error???
sometimes the location.getLatitute() and location.getLatitute() returns null which may cause null pointer Exception..
that may stopped reaching the MyAsyncTask()
check this may help you..
#Override
public void onLocationChanged(Location location) {
double latit =null;
double longi =null;
do
{
latit=location.getlatitude();
longi=location.getlongitude();
}while(latit!=null && longi!=null);
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLatitude());
new MyAsyncTask().execute();
}
The getlatitude() and getlongitude() function will return double value check this documentation
http://developer.android.com/reference/android/location/Location.html#getLatitude()

Oops My Bad!
The correct code is
#Override
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
new MyAsyncTask().execute();
}

Related

FusedLocationProviderClient returns wrong latitude and longitude

Following the examples from google developers site, I use FusedLocationProviderClient to get de last known location.
private FusedLocationProviderClient fusedLocationClient;
// ..
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
And on button click, I call:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
myposition.setText(location.getLatitude() + ", " + location.getLongitude());
// ...
}
}
});
But, sometimes, it gives me a location that is far from current device geoposition. I've checked it on three different devices. I have declared:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
How should I use fusedlocation to get the best position with accuary? I've tried to change getlastlocation with getcurrentlocation but this last method is not available, although the docs said it is available.

Opening maps via intent with preselected location

I'm trying to make an app that will use an Place autocomplete fragment in one activity and when I select a place in it, on a click of a button, I'm supposed to open another activity (Google Maps activity) and it's supposed to get the location that I chose in the first one. I've tried passing Longitude and Latitude from Main class to Maps class, but it just crashes my app. Anyone have any idea how to fix?
Thank you in advance!
EDIT: Sample of what I've tried so far:
/*This is the main class where my autocomplete fragment is*/
Double Lat;
Double lang;
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
// Lat = place.getLatLng().latitude;
// lang = place.getLatLng().longitude;
setLang(place.getLatLng().longitude);
setLat(place.getLatLng().latitude);
Log.i(TAG, "Place: " + place.getName());
}
public void setLang(Double langg){
this.lang = langg;
}
public void setLat(Double Latt){
this.Lat = Latt;
}
public Double getLang(){
return lang;
}
public Double getLat(){
return Lat;
}
/* This is the maps class */
MainActivity maAct;
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng place = new LatLng(maAct.getLat(), maAct.getLang());
// LatLng paris = new LatLng(48.8566, 2.3522);
mMap.addMarker(new MarkerOptions().position(place).title("Marker inPlace"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
}
Ok, you may consider to pass the latitude and longitude by Intent.
// MainActivity
Intent intent = new Intent(MainActivity.this, MapActivity.class);
intent.putExtra("lat", Lat);
intent.putExtra("lng", lang);
startActivity(intent);
And..
// Map Activity onMapReady
double lat = getIntent().getDoubleExtra("lat", DEFAULT_LAT);
double lng = getIntent().getDoubleExtra("lng", DEFAULT_LNG);
LatLng place = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(place).title("Marker inPlace"));
You cannot getValue by maAct, your concept is incorrect.
First if you just
MainActivity maAct;
maAct is not assigned any 'value', so that if you call any methods of maAct, you will get NullPointerException.
Besides, if you really give it a 'value',
// it is totally wrong, just an example only
MainActivity maAct = new MainActivity();
But it is not the same reference so that you cannot get the values you stored before.
What i understand is you want to navigate to the passed latitude and longitude.Here is a sample
String uri = String.format(Locale.ENGLISH, "google.navigation:q=%f,%f", Double.parseDouble(latitude), Double.parseDouble(longitude));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
if(intent.resolveActivity(context.getPackageManager())!=null)
context.startActivity(intent);
You can find more info like creating markers and all here
Edit:
As per your code you want to set the marker.Here is the steps and sample for a working marker example.

Runtime Exception when a location is declared- Android

I have a separate class GPSTracker.java which returns the current latitude and longitude.
public class Live extends Activity implements LocationListener
{
GPSTracker gps;
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
Location oldLocation = new Location(LocationManager.GPS_PROVIDER);
float distanceTravelled=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
startactivity();
}
startactivity:
public void startactivity()
{
gps = new GPSTracker(Live.this);
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
}
else
{
gps.showSettingsAlert();
}
}
Whenever I do that commented out part, it gives an exception even if I declare the location outside the startactivity() in the Live class. Otherwise it displays the correct latitude and longitude.
I want to use it to calculate distance travelled, like this:
#Override
public void onLocationChanged(Location location)
{
oldLocation.set(newLocation);
startactivity();
distanceTravelled+=newLocation.distanceTo(oldLocation);
String stringdistance= Float.toString(distanceTravelled);
TextView distance = (TextView) findViewById(R.id.textDistance);
distance.setText(stringdistance);
}
Is that logic correct?
And the onLocationChanged() does not finds the newLocation in the startactivity(). How can I do that?
But first thing is I get an exception when I use location in startactivity().
But first thing is I get an exception when I use location in startactivity().
Location newLocation;
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
You are trying to execute above code, but see newLocation is null (by default value) and you are trying to use null instead of Object and it results in NullPointerException.
In order to create a new object in Java, you have to use:
Location newLocation = new Location("test");
You are trying to set the longitude and latitude to a non-object. This creates a NullPointerException. You have to create the ojbect location before you use it.

Android, how to show active GPS coordinates in self-made app

Is there any code that lets you show your active coordinates in a self-made app? I am having troubles with my google maps and want to see what my active coordinates are. I prefer to show it as I am looking at the google maps in my app ie like a second layer of information. Thanks all !
You can set up a LocationListener.
In the onLocationChanged callback, you will receive a Location. You can then .getLatitude() and .getLongitude() from the location, and apply it to your layout.
public class MyActivity extends MapActivity implements LocationListener {
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
requestFineAccuracyLocationUpdates();
}
private void requestFineAccuracyLocationUpdates() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 5000, 1000, this);
}
}
#Override
public void onLocationChanged(Location location) {
/* You can get your latitude and longitude here, and do whatever. */
}
}

Android Variable Scope; or, where the heck is my string

I'm working on a simple Android app, with a GPS listener and a webview.
I can get the latitude and longitude with no issue. The problem is, I want to put the latitude and longitude into a URL (like myurl.com/mypage.php?lat=57&lon=21)... but the variable the data is stored in is confined to its class. I can't figure out how to declare or create a variable that I can use throughout the entire main class. Here's my code:
public class WTest2Activity extends Activity {
public String txt;
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
txt = "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude();
Toast.makeText( getApplicationContext(),txt,Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {} /* do nothing */
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
WebView webview;
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.myurl.com/page.php?this=" + txt);
}
}
Your OnCreate method is the method called at start of Activity. At that time, txt is null. That's why it doens't show in your url. Then, onLocationChanged sets the value of txt but where are you using this afterwards? nowhere!.
you should move what you do in onCreate to onLocationChanged:
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
txt = "Latitude: " + loc.getLatitude() + "Longitude: " + loc.getLongitude();
Toast.makeText( getApplicationContext(),txt,Toast.LENGTH_SHORT).show();
webview.loadUrl("http://www.myurl.com/page.php?this=" + txt);
}
add a new line here:
public class WTest2Activity extends Activity {
public String txt;
public Location location;
then, in your public void onLocationChanged(Location loc), try setting location.setLatitude(loc.getLatitide); and location.setLongitude(loc.getLongitude);
then, you can access your location anywhere with your global variable location
Buddy its just small logical mistake in your code. Let me explain. You are requesting location updates then right after that you are loading URL. Now location listening is different thread which is updating value of txt variable. And updating location takes time. And taken time can be different every time. That is why you need to move your loadUrl code to onLocationChanged method.

Categories