I am trying to get a user’s location when a button is clicked.
I have the following code in my button onclick listener:
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location currentLocation = locationManager.getLastKnownLocation(bestProvider);
Log.e(tag,"reached till here");
location = Double.toString(currentLocation.getLatitude()) + " " + Double.toString(currentLocation.getLongitude());
Toast.makeText(getApplicationContext(), location, Toast.LENGTH_LONG);
MyLocation.setText(location);
I am getting the the output reached till here in logcat. After that the application stops and asks me to force close it. I initially did some searching and found out that getLatitude and getLongitude return double values. So I corrected the code. But still I am getting an error. What am I doing wrong?
EDIT : The logcat error:
Got RemoteException sending setActive(false) notification to pid 796 uid 10036
I think currentLocation is returning null
If your are testing your app in the
Emulatoryou probably don’t have any provider and thecurrentLocationobject is null and that is whygetLatitude()andgetLongitude()will give a NPE.Edit: as the @grinnner said, from the DDMS perspective you can simulate the sending of location coordinates. Open the DDMS Perspective in eclipse and in the LocationControls tab set the Longitude and Latitude and then click send. Be sure that the focus in the Devices tab is on the emulator that you are running your app on.