I am trying to get a location (latitude, longitude) on my Android smartphone (HTC Desire HD), using Wifi-network and GPS.
This is the code I use, only I keep getting "Location not available"
Iam working with Eclipse IDE.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import com.example.shortsproject.R;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class LocationGetter extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.locationtext);
longitudeField = (TextView) findViewById(R.id.locationtext2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* 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) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Can someone help me with this?
Related
I am having trouble implementing a LocationListener.
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView latitudeTV;
TextView longitudeTV;
TextView altitudeTV;
TextView locationNameTV;
double latitude;
double longitude;
double altitude;
String locationName;
LocationManager locationManager;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTV = (TextView) findViewById(R.id.latitude);
longitudeTV = (TextView) findViewById(R.id.longitude);
altitudeTV = (TextView) findViewById(R.id.altitude);
locationNameTV = (TextView) findViewById(R.id.locationName);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
altitude = location.getAltitude();
locationName = "Placeholder";
longitudeTV.setText("Longitude: \n" + longitude + "°");
latitudeTV.setText("Latitude: \n" + latitude + "°");
altitudeTV.setText("Altitude: \n" + altitude + "m");
locationNameTV.setText("Location: \n" + locationName);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
}
}
I'm not sure if it's a syntax issue or a scoping issue, but I keep getting "unable to resolve symbol" errors. It's acting like I haven't implemented the LocationListener methods. I have tried adding implements LocationListener to MainActivity and that shows an error saying I have not implemented the LocationListener methods. I'm not sure where my mistake is.
EDIT:
I've changed my code per your answers. When I try to implement //locationManager.requestLocationUpdates(Context.LOCATION_SERVICE, 5000, 0, this); I get the following when trying to launch the app: LocationTestApp keeps stopping. I've commented out that line, and the app works again.
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView latitudeTV;
TextView longitudeTV;
TextView altitudeTV;
double latitude;
double longitude;
double altitude;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTV = (TextView) findViewById(R.id.latitude);
longitudeTV = (TextView) findViewById(R.id.longitude);
altitudeTV = (TextView) findViewById(R.id.altitude);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//locationManager.requestLocationUpdates(Context.LOCATION_SERVICE, 5000, 0, this);
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
altitude = location.getAltitude();
longitudeTV.setText("Longitude: \n" + longitude + "°");
latitudeTV.setText("Latitude: \n" + latitude + "°");
altitudeTV.setText("Altitude: \n" + altitude + "m");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
A LocationListener class, in this case an Activity, should be defined as below:
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends AppCompatActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this); // Note: You pass this, so the overridden methods
}
#Override
public void onLocationChanged(Location location) {
// Do your stuff here
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
And this is the solution in jle's comments.
But if you want to use the locationListener that you've declared in your onCreate, you should declare it before using it, in this way:
...onCreate(...) {
...
LocationListener locationListener = new LocationListener() {...} // Define this...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener); // ...and then call this
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
I have two question with my code
can not enter the onLocationChanged() function
mylocation is always null
I also add the permission and turn on my device GPS function
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name ="android.permission.ACCESS_COARSE_LOCATION"/>
follows is my code please help me to get Latitude Lontitude thanks all.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Getaddress getaddress = new Getaddress();
getaddress.excute();
}
public class Getaddress implements LocationListener {
Geocoder geocoder;
private Location mylocation;
private double Latitude;
private double Lontitude;
private LocationManager locationManager;
public Getaddress() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
mylocation = locationManager.getLastKnownLocation(provider);
Boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.w("isGPSEnabled",isGPSEnabled.toString());
}
public void excute()
{
Latitude = mylocation.getLatitude();
Lontitude = mylocation.getLongitude();
Toast.makeText(SecondActivity.this, "Latitude"+Double.toString(Latitude),Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location)
{
mylocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Xml File :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/str_tv_location"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_location"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_longitude"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Java file:
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Permission :-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
At first: you need GPS available space.
Secondly: your location is always null, because your space for GRP LOCATION not available. You need to check if GPS working or not
onLocationChanged method work every time when your location changed.
public class GPSTracker implements LocationListener {
public GPSTracker(Context con){
LocationManager lm = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// do something here...
//location.getLatitude();
//location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
i am trying google maps api on my android phone via following code. My app locating my phone and working great but gps notification icon not blinking. How can i blink gps icon when locating my phone.
Thanks For Replies.
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And The Code :
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.EditText;
import android.widget.Toast;
public class main extends MapActivity {
MapController mControl;
GeoPoint geoP;
MapView mapV;
MyLocationOverlay compass;
EditText etext;
String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etext = (EditText) findViewById(R.id.latLong);
mapV = (MapView) findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enable) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = location.getLatitude() * 1E6;
Double longi = location.getLongitude() * 1E6;
geoP = new GeoPoint(lat.intValue(), longi.intValue());
List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
compass = new MyLocationOverlay(this, mapV);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoP, "Hola, Mundo!","I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapV.getOverlays().add(compass);
mapOverlays.add(itemizedoverlay);
mControl = mapV.getController();
mControl.animateTo(geoP);
mControl.setZoom(5);
mControl.setCenter(geoP);
locationManager.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
if (status == LocationProvider.AVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.AVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.OUT_OF_SERVICE",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
"Location Changed", Toast.LENGTH_SHORT).show();
}
});
//etext.setText(String.valueOf(lat) + "," + String.valueOf(longi));
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
compass.disableCompass();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
}
protected boolean isRouteDisplayed() {
return false;
}
t0mm13b, working on my handset but GPS notification icon not blinking. Virtual Device means Emulator. I solved problem.
Code :
package com.yunusoksuz.gmapstest;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class YnsmapsActivity extends Activity implements LocationListener {
/** Called when the activity is first created. */
private LocationManager locationManager;
private Location location;
private String provider;
private Double lat, longi;
private Criteria criteria;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
public void onLocationChanged(Location location) {
Toast.makeText(
this,
"Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();
tv.setText("Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude());
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Now gps notification blinking.
I need a simple android app which can be installed on any android supporting device; I need this app to send the coordinates of its current location every 5 minutes so that it can be sent to sql database
Thanks
This is the code from which i am showing my current location and getting the co-ordinates values(as toast message for now)
Now i need to send this location co-ordinate to the database after every 5 minutes
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.iconnectgroup.LocateDeviceApp.Gps.MyPositionOverlay;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class HelloGoogleMaps extends MapActivity {
MapController mapController;
MyLocationOverlay myLocationOverlay ;
MyPositionOverlay positionOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(17);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
mapView.setStreetView(true);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "Truck location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_LONG).show();
Log.e("co-ordinates are:", Text);
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_LONG ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
myLocationOverlay.disableCompass();
myLocationOverlay.disableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
What I am doing is trying to get a basic GPS working and can't figure out the problem (there is no errors coming up). When i run it on the emulator it crashes. I am using android 2.2
package Weather.app;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class WeatherAppActivity extends Activity{
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected LocationListener MyLocationListener;
protected Button findButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findButton = (Button) findViewById(R.id.findButton);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
(LocationListener) this
);
findButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
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(WeatherAppActivity.this, message,
Toast.LENGTH_LONG).show();
}
final class MyLocationListener implements LocationListener {
#Override
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(WeatherAppActivity.this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(WeatherAppActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
}
This is also in my manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
I have updated this code as I have made a few changes
Here is one example of working basic GPS activity:
public class UseGpsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
double lati = loc.getLatitude();
double longi = loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + lati + "Longitud = " + longi;
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Unless some code is missing in your post MyLocationListener (you should not user upper case identifiers for instance fields!) is not initialized when passing the reference (i.e. null) to requestLocationUpdates().
You don't need to create another LocationListener, the statement
WeatherAppActivity extends Activity implements LocationListener
and the overriden methods
#Override
public void onLocationChanged(Location location)
etc means you have one in your main class already, so get rid of the inner class MyLocationListener completely.
Put your Toast code etc inside the overriden listener methods in the main class.
Then in onCreate() have :
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
this
);
I have a tutorial on Android location services on my blog. I'm not sure of your specific error but you can look at the code to see if it helps you!
http://www.scotthelme.co.uk/blog/android-location-services/