Android duplicates activity when minimized, then maximized - java

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..

Related

The app crashed after sending location to server Android Java

I am able to send the location (String address) + messages to my server; however, my app crashed after sending data to server. I used Volley library to make a POST request. Can someone help me fix this issue?
First I get the location and the list of the address.
public class MainActivity extends AppCompatActivity {
//Declare LocationManager and LocationListener
LocationManager locationManager;
LocationListener locationListener;
String address = "Unable to get the address!";
EditText Message;
AlertDialog.Builder builder;
String server_url ="https://schoolserver-tand089.c9users.io/Report.php";
//Process when users give the permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Start the location service
startListening();
}
}
//Checking permission granted method
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
//Update location method. 1 variable location
public void updatedLocationInfo(Location location) {
Log.i ("Location", location.toString());
//Cast the textViews
TextView latTextView = (TextView) findViewById(R.id.txtLat);
TextView lonTextView = (TextView) findViewById(R.id.txtLong);
TextView altTextView = (TextView) findViewById(R.id.txtAltitude);
TextView accTextView = (TextView) findViewById(R.id.txtAccuracy);
//get the string from location
latTextView.setText("Latitude: " + location.getLatitude());
lonTextView.setText("Longitude: " + location.getLongitude());
altTextView.setText("Altitude: " + location.getAltitude());
accTextView.setText("Accuracy: " + location.getAccuracy());
//Create Geocoder object to Get the address
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
//Using try/catch to prevent the app from crashing when failing to get Addresses
try {
//Declare the error string
//String address = "Unable to get the address!";
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
//Check if the address is valid
if (listAddresses != null && listAddresses.size() > 0) {
//Set address to empty string again when we know it is working
address = "Address: \n";
// Log.i("Address", listAddresses.get(0).toString());
//check for every item in the list Addresses is valid
if (listAddresses.get(0).getSubThoroughfare() != null) {
address += listAddresses.get(0).getSubThoroughfare() + " ";
}
//Street name
if (listAddresses.get(0).getThoroughfare() != null) {
address += listAddresses.get(0).getThoroughfare() + "\n";
}
//City name
if (listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + "\n";
}
//Zip code
if (listAddresses.get(0).getPostalCode() != null) {
address += listAddresses.get(0).getPostalCode() + "\n";
}
//Country name
if (listAddresses.get(0).getCountryName() != null) {
address += listAddresses.get(0).getCountryName() + "\n";
}
TextView addressTextView = (TextView) findViewById(R.id.txtAddress);
//set the address into the text View
addressTextView.setText(address);
//Log.i("Address", address.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up locationManager and locationListener above and cast them into their type
//Using built-in location service
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
//Get the location when it changes
#Override
public void onLocationChanged(Location location) {
//call the updated location above
updatedLocationInfo(location);
}
//
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Check for the version of SDK
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
// above 23 we need to check for permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//ask for permission. Number 1 is just a request queue.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
//we have permission
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//Get the last location from the built-in GPS
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//In case location does not have lastknownlocation, we call the updatedLocation method above
if (location != null) {
updatedLocationInfo(location);
}
}
}
}
Next, I used the onClick method to send the Address and a message to server when user clicks the button.
// using onClick
public void bntTap (View bnt) {
Message = (EditText) findViewById(R.id.message);
//Hide virtual keyboard after click the button
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
final String message;
message = Message.getText().toString();
if (message.equals("")) {
builder.setTitle("Unable to report");
//Creating a AlertDialog to display errors
AlertDialog alertDialog = builder.create();
alertDialog.setMessage("Please Enter All Required Fields*");
alertDialog.show();
} else {
//Post request
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//get response form server to check if it is successfully submitted
builder.setTitle("Server Response");
builder.setMessage("Congratulation" + " " + response);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Message.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//send data to mySQL server
//the keys must be same as field names in mySQL server
// get the list of the address
params.put("LOCATION", address);
params.put("MESSAGES", message);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addTorequestqueue(stringRequest);
//Log.i("Address", address.toString());
}
}
All the data successfully sent to the server, but the app crashed.
Updated: logcat when crashing
logcat when crashing
You are getting an NPE, as you forgot to define builder. You have only declared it in your code as
AlertDialog.Builder builder;
Please define the builder as
builder = new AlertDialog.Builder(MainActivity.this);
in your onCreate().

How do I get android location once at the push of a button?

I am currently making an application where I need to get the user's location when a button is clicked. I am using this sample and it works great as a sample application. My question is, how would I implement it into my application button's onClick event? I don't need it to refresh often, I just need it so that when the user clicks the button, it gets the user's latitude and longitude and saves them to two variables. What would be the best way to do this? I didn't post my own code because all I have is a button with an onClick event.
Follow these steps to get the location on button click:
Implement LocationListener in your activity like:
public class MainActivity Extends AppCompactActivity implements LocationListener
Then create an Instance For LocationManager, longitude, and latitude as below:
LocationManager locationManager; // create global outside all methods
Double currentLattitude, currentLongitude;
Set click event on your button as below:
btnLocation.setOnClickListner( new View.onClickListner
{
#Override
public void onClick(View v)
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
});
Now implement method for LocationListener as below:
#Override
public void onLocationChanged(Location location) {
currentLattitude = location.getLatitude();
currentLongitude = location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
With this, you can get your location via on click of your button.
Main thing to don't forget is to set permission (in your Manifest) as below:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Use fused location API this is the fastest from all others.
public class LocationActivity extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
LocationListener provides call back for location change through onLocationChanged.
GoogleApiClient.ConnectionCallbacks provides call back for GoogleApiClient onConnected.
GoogleApiClient.OnConnectionFailedListener provides call back for GoogleApiClient onConnectionFailed.
Source: http://javapapers.com/android/android-location-fused-provider/

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...

Locationmanager getLastKnownLocation always null

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.

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