Locationmanager getLastKnownLocation always null - java

i have a problem. When i test this. and i ask for the showCurrentLocation function it always returns null. It works in the emulator when i send the location after. But i need this to work on the phone, and there you can't send the location like in de DDNS window.
Here's my code
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
protected Button stopLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
/*stopLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//locationManager.removeUpdates(MyLocationListener) ;
}
}); */
}
public String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
protected void showCurrentLocation() {
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(crit, true);
Location loc = locationManager.getLastKnownLocation(provider);
if (loc != null) {
String longi = "" + loc.getLongitude();
String lat = "" + loc.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
longi,
lat,
num );
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
if (loc == null)Toast.makeText(LbsGeocodingActivity.this, "Null ",
Toast.LENGTH_LONG).show();
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
String longi = "" + loc.getLongitude();
String lat = "" + loc.getLatitude();
String num = getMyPhoneNumber();
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s \n %3$s ",
longi,
lat,
num );
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
My permissions are: FINE_LOCATION COURSE_LOCATION.
I really just want it that it tracks the users location, even on the background..

You can sent mock locations also to your Android device see
Android mock location on device?
Then besides that I had this problem too it seems it maybe never had a location before on your device try to open google maps and make sure you get located and then try again. Also I suspected something like first time you use the application you don't have access to a last know location yet because you never used it so you first need to get located and next time you startup the application it will work. If you want a quick location try to get located by wifi or cell towers
And make sure the permissions are set!

did you checked the GPS is switched on in your phone, after switching on GPS it will take some time to get the location updates.

Related

location returns null when started the first time

For my app, I need to get the location of the user, to fetch corresponding data from a server. The problem is that the code I use doesn't properly return the location when it's opened the first time. After restarting the app once it works just fine. I searched the other questions and found out, that if you use getLastKnownLocation and there is no location since the last reboot, it returns null. But why does it work when the app is restarted? Does it fetch it when it's opened the first time, and how can I make it wait until the location is fetched properly at the first opening then?
The code of my MainActivity:
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else {
progressBar.setVisibility(View.VISIBLE);
GPSClass gt = new GPSClass(getActivity().getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
//Toast
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
And the GPSClass:
public class GPSClass implements LocationListener {
Context context;
public GPSClass(Context context) {
super();
this.context = context;
}
public Location getLocation(){
if (ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
Log.e("fist","error");
return null;
}
try {
LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,this);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return loc;
}else{
Log.e("sec","error");
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Here is the full tutorial
I shared a tutorial link follow that link.
Call this below method. It will return value; when lat and long is found. Until object is null or doesn't return any value your app must be idle or show some progress value or tell the user to wait.
InitGeoLocationUpdate.locationInit(SplashScreen.this,
object -> {
double latitude = object.latitude;
double longitude = object.longitude;
Lg.INSTANCE.d(TAG, "Current Location Latitude: " + latitude + " Longitude: " +
longitude);
});
Try this this will not give you null current location
class GetLastLocation extends TimerTask {
LocationManager mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;
public GetLastLocation(Handler mLocHandler) {
this.mLocHandler = mLocHandler;
}
#Override
public void run() {
timer.cancel();
mlocManager.removeUpdates(mlocListenerTmp);
Location location = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
{
if (mlocListenerTmp != null) {
mlocManager.removeUpdates(mlocListenerTmp);
}
currentLocation = location;
}
if (location != null) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Log.d("loc", " :" + message);
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Log.d(
"loc",
":No GPS or network signal please fill the location manually!");
location = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLocation = location;
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", false);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
}
}
}
}
call it like this in your MainActivity
timer.schedule(new GetLastLocation(mLocHandler), 3000);
and the customLocationclass is as follows:
public class CustomLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
currentLocation = loc;
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
Log.d("loc", "onLocationChanged" + Text);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}

Android duplicates activity when minimized, then maximized

I have google searched this with no success and seams very strange to me.
I am building a simple GPS app that send co-ordinates with HttpRequest, though I have noticed when minimising the UI then maximising, It runs a duplicate of the same activity. and doubles up on HttpRequest's
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
processExtraData();
}
private void processExtraData() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, 5, this);
}
#Override
public void onLocationChanged(Location location) {
Bundle extras = getIntent().getExtras();
String driver_id = extras.getString("driverid");
String msg = "Driver:" + driver_id + "\nCurrent Location:\nLatitude: " + location.getLatitude()
+ "\nLongitude: " + location.getLongitude();
new HttpRequestTask(
new HttpRequest("https://www.autoflora.net/driver/gps.php?user_id=" + driver_id + "&latlong=" + location.getLatitude() + "*" + location.getLongitude(), HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
#Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
String s = calc.getText().toString();
calc.setText(s + "1")
TextView driver = (TextView) findViewById(R.id.driver);
driver.setText("" + driver_id);
TextView Longitude = (TextView) findViewById(R.id.longitude);
// Getting reference to TextView tv_latitude
TextView Latitude = (TextView) findViewById(R.id.latitude);
// Setting Current Longitude
Longitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
Latitude.setText("Latitude:" + location.getLatitude());
// Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
noticed when minimising the UI then maximising
There's neither minimising nor maximizing of UI on Android. You apparently start the activity again via launcher (this is most likely your maximizing thing) which creates new instance of you activity. If you want just single instance allowed no matter what, you must set system so by using android:launchMode in declaration of activity in your manifest file. See docs here for possible options.
#Override
public void onStart() {
super.onStart();
Toast.makeText(getBaseContext(), "start", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getBaseContext(), "resume", Toast.LENGTH_LONG).show();
locationcheck(); // checks permissions
}
#Override
public void onPause() {
super.onPause();
Toast.makeText(getBaseContext(), "pause", Toast.LENGTH_LONG).show();
}
#Override
public void onStop() {
super.onStop();
// locationManager.removeUpdates(this);
Toast.makeText(getBaseContext(), "stop", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(), "destroy", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
finish();
}
Seems to have fixed it..

Android get GPS coords in Async method

i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* #param lat
* double
* #param lon
* double
* #return List <Address>
* #throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
If i'm trying to get GPS coords using the:
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
I got following exception in doInBackground:
cannot create handler inside thread that has not called looper.prepare
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
Create the handler in the AsyncTask's constructor. You must make it on a thread with an active message loop, like the UI thread.
Getting the location is already an async operation...
All you need to do is to call it on the UI thread, and expect new results soon afterwards (depends on many things).
That's why it has a listener. Otherwise it would just return you a response while blocking you...

app crashes when intent passes variable to another activity

i am making a app that tracks the user and tracks another user which in theory would be an animal.
my app goes like this, you register a username and pass then when this is done the user can log into the map by reentering the correct username and password. This is where the issues begin.
upon creation of the screen the map loads with the users current location and auto sends a sms to the "animals" phone to request gps details, this then sends back 2 sms messages, 1 containing the gps information. i have a SmsReceiver class which reads this information and extracts the longitude and latitude data, converts it into a double then passes it to the map activity to be converted into a lnglat variable and displayed on the google map with a marker. Now the issue i am having is that it can take several minutes for the sms to return with the gps information, when this is done and the intent is used to send the coordinates to the map page a button must be clicked so that the longitude and latitude are combined into the AnimalCoordinate and the marker is shown, however because og the time gap its imposible to press the button at the same time the sms is retrieved and it causes a crash as the data is being sent from the smsreceiver class to nothing on the other side, and if i take the intent out of the onclick method the same thing happens but in reverse, the map runs the intent but the informaion is not there yet and it crashes.
any help would be greatly appreciated as this has been a nightmare.
i am also sorry if i overcomplicated the explanation, i wanted to ake sure it was explained as best i could.
the code is below for the two classes.
Map class
public class MainScreen extends FragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private String provider;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
map = ((SupportMapFragment)getSupportFragmentManager().
findFragmentById(R.id.map)).getMap();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(this, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
// Sets the map type to be "hybrid"
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Bundle b = getIntent().getExtras();
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(this, "Location " + lat+","+lng,
Toast.LENGTH_LONG).show();
LatLng Usercoordinate = new LatLng(lat, lng);
Marker User = map.addMarker(new MarkerOptions()
.position(Usercoordinate)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//Move the camera instantly to user with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Usercoordinate, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
//Sends sms to 'animal phone'
String phoneNo = "***********";
String sms = "GPSLocation";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void map_help(View view) {
//method for the help button
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Help");
// set dialog message
alertDialogBuilder
.setMessage("Click the 'Pet' button to display the pets location." +
"This can take a few minutes to retrieve.")
.setCancelable(false)
.setPositiveButton("ok",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
};
public void Find_Pet(View view)
{
//String phoneNo = "07516909014";
// String sms = "GPSLocation";
// try {
// SmsManager smsManager = SmsManager.getDefault();
//smsManager.sendTextMessage(phoneNo, null, sms, null, null);
//Toast.makeText(getApplicationContext(), "SMS Sent!",
// Toast.LENGTH_LONG).show();
// } catch (Exception e) {
// Toast.makeText(getApplicationContext(),
// "SMS faild, please try again later!",
//Toast.LENGTH_LONG).show();
// e.printStackTrace();
//}
}
public void Show_Pet(View view)
{
//gets coordinates from SmsReceiver
Bundle b = getIntent().getExtras();
double AnimalLat = b.getDouble("key");
Bundle d = getIntent().getExtras();
double AnimalLon = d.getDouble("key1");
LatLng Animalcoordinate = new LatLng(AnimalLat, AnimalLon);
//adds pets marker on map
Marker Animal = map.addMarker(new MarkerOptions()
.position(Animalcoordinate)
.title("Your pet is here")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
SmsReceiver class
public class SmsReceiver extends BroadcastReceiver
{
String lat = null;
String lon = null;
String message = null;
final SmsReceiver context = this;
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += msgs[i].getMessageBody().toString();
}}
message = str.toString();
String[] test = message.split("");
char[] test2 = test[1].toCharArray();
//if the first character of the sms is C then read gps information
if (test2[0] == 'C' || test2[0] =='c')
{
lat = message.substring(45, 56);
lon = message.substring(67, 78);
double AnimalLat=Double.parseDouble(lat);
double AnimalLon=Double.parseDouble(lon);
//Pass coordinates to MainScreen
Intent a = new Intent(getApplicationContext(), MainScreen.class);
Bundle b = new Bundle();
b.putDouble("key", AnimalLat);
a.putExtras(b);
startActivity(a);
Intent c = new Intent(getApplicationContext(), MainScreen.class);
Bundle d = new Bundle();
d.putDouble("key1", AnimalLon);
c.putExtras(d);
startActivity(c);
}else {
}
}
private void startActivity(Intent a) {
// TODO Auto-generated method stub
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}}
I also want to apologize for the layout of the code, this is the first time i have pasted code on this site.
Thanks again.
To be honest, I'm not sure which Button you are talking. The only one I saw was in the AlertDialog unless I missed something. Anyway, you can disable your Button until whatever data has a value or you can do nothing in the onClick() if it is null
//inside your Button
if (data != null)
{
...do stuff in here
}
If you need more clarification then please indicate in the code the data you are talking about and the Button but I think you get the idea.

stopping Locationmanager is not working in a button

Hello could somebody help me with what i'm doing wrong.
I want this application to work in the background, i just want to make in a button where to stop the locationmanager. when i use the removeUpdates, its not working. I cant call that function there.
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 60000; // Minuten(van milliseconden) * aantal
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Button retrieveLocationButton;
protected Button stopLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
stopLocationButton = (Button) findViewById(R.id.stop_location_button);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LocationManager.removeUpdates(locationListener) ; }
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
I really need this badly
Change the code from this (* indicates whats changed *):
***retrieveLocationButton***.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
locationManager.removeUpdates(locationListener) ;
}
});
To this:
stopLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
locationManager.removeUpdates(locationListener) ;
}
});
EDIT:
use locationManager "the global variable which starts with small letter" and not LocationManager "the class which starts with capital letter" for the function removeUpdates()
locationManager.removeUpdates(MyLocationListener);
try this.

Categories