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);
}
Related
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 0; // 1 minute
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean isGPSEnabled = false;
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,enter code here
0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + 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");
}
}
/*************************** Andriod Manifest ****************************** Has this tag also
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Attached is my code. It is returning isGpsEnabled as true, but OnLocationChanged event is not fired, Please suggest. I need it very important. If I use the same code using "Network provider" it is working and reurning current location latitude & longitude.
I've been following some tutorials and creating some simple android apps but I'm having some trouble with that one it only consists in showing the current location (longitude, latitude, altitude).
Any ideas about whats going on? Thanks in advance!
package com.ricard.location.app;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textLat;
TextView textLong;
TextView textAlt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);
textAlt = (TextView) findViewById(R.id.textAlt);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class mylocationlistener implements LocationListener{
#Override
public void onLocationChanged(Location location){
if(location != null)
{
double plong = location.getLongitude();
double plat = location.getLatitude();
double palt = location.getAltitude();
textLat.setText(Double.toString(plat));
textLong.setText(Double.toString(plong));
textAlt.setText(Double.toString(palt));
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}
There was an error with the reception of the signal on this device I tested it on a new one and it worked so it was a Hardware error thought.
Thanks!
private void moveToCurrentLocation() {
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getContext().getSystemService(LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLong latLong = new LatLong(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition()
.target(latLong).zoom(whateverZoomThatYouWant);
map.animateCameraTo(cameraPosition);
}
// that is for fragment if you use it in activity delete --> getContext()
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?
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/
how can i pass latLongString to elhActivity and show it on the screen....both java files are under same package com.elh.whereami;
i used putExtra and getExtars with intent and still nothing is showing on the screen
this is the whereami.java code
package com.elh.database;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
//import android.widget.TextView;
public class whereami extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
public void updateWithNewLocation(Location location) {
String latLongString;
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
Intent intent = new Intent(this, elhActivity.class);
intent.putExtra("the_latLongString", latLongString);
startActivity(intent);
}
}
and this is the elhActivity.java
package com.elh.database;
import android.app.Activity;
import android.widget.TextView;
public class elhActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String latlonginfo = getIntent().getStringExtra("the_latLongString");
TextView tv = new TextView(this);
tv.setText(latlonginfo);
setContentView(tv);
}
}
getIntent().getExtra() will return a Bundle object which contains the objects you place using putExtra().
For example:
Bundle arguments = getIntent().getExtras();
String latlonginfo = arguments.getString("the_latLongString");
TextView tv = new TextView(this);
tv.setText(latlonginfo);
setContentView(tv);
Intent myIntent = this.getIntent();
String latlonginfo = myIntent.getStringExtra("the_latLongString");
The problem might be you are using setContentView twice in your code.
setContentView(R.layout.main);
setContentView(tv);
You will probably have to do away with the 1st setContentView.
or better still add a TextView in the layout in design time and intialize your textview with latlonginfo.
Consider creating a separate XML layout, say child_dialog.xml for the second activity.
public class ChildActivity extends Activity {
private String pushedValue;
#Override
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.child_dialog);
try {
pushValue= getIntent().getExtras().getString("the_latLongString");
}
catch(Exception e){
pushValue= "";
}
}
}