I am basically testing using the location for my android app. All it currently does is show some TextViews with the latitude and longitude of the user's location. However, what I wish to have is for the LocationListener to stop receiving updates after it has received a location, not for it to continue listening for updates.
public void updateLocation(Location location, Geocoder geocoder){
TextView lat=(TextView)getView().findViewById(R.id.lat);
TextView longt=(TextView)getView().findViewById(R.id.longt);
double lata=location.getLatitude();
double longa=location.getLongitude();
lat.setText(Double.toString(location.getLatitude()));
longt.setText(Double.toString(location.getLongitude()));
}
public void FindLocation(Context context){
final LocationManager locationManager=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
updateLocation(location);}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
This should be done after updateLocation() has been called but it cannot reference locationManager nor locationListener. I also cannot call it inside FindLocation() after updateLocation() has been called as 'Cannot refer to a non-final variable locationListener inside an inner class defined in a different method'. However, adding final to locationListener only yields the error 'locationListener may not have been initialised'. Is there anyway I can achieve this?
Make locationManager a class variable and final so you can reference it from anywhere within the class.
private final LocationManager locationManager;
and then define it inside onCreate like below:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager =(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
updateLocation(location);}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
Seems to me what you are looking for is to use the locationListener itself in one of its methods. You can do this with 'this'.
public void FindLocation(Context context){
final LocationManager locationManager (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
updateLocation(location);
locationManager.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
Make it a private field of the class, like this:
private LocationManager mLocationManager;
public void FindLocation(Context context){
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
...
}
Now you can access mLocationManager from anywhere in the class.
Related
I am trying to write an Android app for deliveries. A big part is finding the current location of the mobile device.
All the tutorial I have followed all give the same error which I can not figure out or understand, I am new to Android Development.
The error I receive is "Error:(76, 5) error: method does not override or implement a method from a supertype".
My code:
public class LoginActivity extends AppCompatActivity {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
String tempLocation;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
public static String pName;
public static String pID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Get Input
etUsername = (EditText) findViewById(R.id.txtLoginUserName);
etPassword = (EditText) findViewById(R.id.txtLoginPassword);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
tempLocation = "Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude();
TextView lg = (TextView) findViewById(R.id.txtLoginUserName);
lg.setText(tempLocation);
}
#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");
}
And My Result Log:
Error:(76, 5) error: method does not override or implement a method from a supertype
Error:(83, 5) error: method does not override or implement a method from a supertype
Error:(88, 5) error: method does not override or implement a method from a supertype
Error:(93, 5) error: method does not override or implement a method from a supertype
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1.661 secs
Information:5 errors
Information:0 warnings
Information:See complete output in console
I am using this tutorial.
Any help or advise would be appreciated, as I have tried to use many different answers but non really help so far.
You are missing the following implements LocationListener in your class...
Use something like this
class LocationActivity extends AppCompatActivity implements LocationListener{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
and then you will be able to achieve what you are trying to....Hope it helped you
Possible duplicate:
Refer to this post #GoodDisplayName
Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this
I'm stuck with these problem several day now, I don't know what is my problem is. I really need some help now, hopping can help me out here. These is my code.
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView text;
String trip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.id_trip);
scheduleAlarm();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
public void onLocationChanged(Location location) {
new MyAsyncTask ().execute();
}
public class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
trip = "Hai";
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
text.setText(trip);
}
}
public void scheduleAlarm() {
Intent intent = new Intent(getApplicationContext(), Track.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, Track.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 60 * 1000, pIntent);
}
}
Services class
public class Services extends Service {
public LocationManager locationManager;
public MainActivity listener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MainActivity();
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, listener, null);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}}
Track class
public class Track extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, Services.class);
context.startService(i);
}}
And the error are :
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.findViewById(int)' on a null
object reference
Thanks
Here is your error :
TextView text = (TextView) main.findViewById(R.id.id_trip);
text.setText(string);
you cannot get TextView object like this from Service. Either create TextView object as static or use BroadcastReceiver.
You are returning null value from doInBackground, that is the reason you are getting NullPointerException.
Change MyAsyncTask code with the following code.
public class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
if(text==null){
text = MainActivity.this.findViewById(R.id.id_trip);
}
}
#Override
protected String doInBackground(String... arg0) {
trip = "Hai";
return trip;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
text.setText(strFromDoInBg);
}
}
Remove below 2 lines from setText(String str) methood.
MainActivity main = new MainActivity();
TextView text = (TextView) main.findViewById(R.id.id_trip);
Hope this will help you.
Guys how Do I change the class signature to implement googleapiclient? If you click on image it shows the tutorial but doesn't show clearly what to do. I don't understand when it says implement it because I don't know how? Can anyone help?
Here is my code:
public class MainActivity extends ActionBarActivity {
//private LocationManager locationManager;
private Location currentLocation;
private TextView locationText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationText = (TextView) findViewById(R.id.textView1);
}
private void updateDisplay(){
if (currentLocation==null){
locationText.setText("determining your location...");
} else {
locationText.setText(
String.format("Your location:\n%2f, %.2f", currentLocation.getLatitude(),
currentLocation.getLongitude()));
}
}
private LocationListener mListener = new LocationListener(){
#Override
public void onLocationChanged(Location location){
currentLocation=location;
updateDisplay();
}
#Override
public void onProviderDisabled(String provider){
}
#Override
public void onProviderEnabled(String provider){
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
#Override
public void onResume(){
super.onResume();
//currentLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
updateDisplay();
//locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, mListener);
}
#Override
public void onPause(){
super.onPause();
//locationManager.removeUpdates(mListener);
}
how Do I change the class signature to implement googleapiclient?
Add implements GoogleApiClient.ConnectionCallbacks to your class, and implement the methods that it requires.
I do use the Google Maps API v2 to get my location on the map. Is it possible to write the correct address in the information of the marker?
I didn't find anything useful in the internet..
Here is my code. Thanks in advance!
#SuppressLint("NewApi")
public class MainActivity extends Activity implements LocationListener {
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#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
}
}
you want to add extra information on the marker? If i understood correctly then you can add a snipper.
LatLng mark = new LatLng(Double.parseDouble(lat), Double.parseDouble(longi));
map.addMarker(new MarkerOptions().title("MY Position").snippet("Extra info").position(mark));
i finally reached an app that get's the GPS position of the user, but i reached it implementing LocationListener. it works fine, but i need to do it without implementing it, because i have to do a class that doesn't implement methods.
I searched for a lot of tutorials and check a lot of websites and i try to transform my code to not implement LocationListener but i can't do it, every thing i tested broken my app and stop getting the GPS position of the user.
Please, if someone expert on this can transform my code for not be using "implements LocationListener" i'll be grated to him
this is the code to transform:
public class GpsMiniActivity extends Activity implements LocationListener{
private LocationManager mLocMgr;
private TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout rl = new FrameLayout(this.getApplicationContext());
LinearLayout ll= new LinearLayout(this.getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(rl);
rl.addView(ll);
tv1=new TextView(getApplicationContext());
ll.addView(tv1);
//setContentView(R.layout.main);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, this);
}
#Override
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
public class GpsMiniActivity extends Activity {
private LocationManager mLocMgr;
private TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout rl = new FrameLayout(this.getApplicationContext());
LinearLayout ll= new LinearLayout(this.getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(rl);
rl.addView(ll);
tv1=new TextView(getApplicationContext());
ll.addView(tv1);
//setContentView(R.layout.main);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, ll);
}
}
private LocationListener ll = new LocationListener(){
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
There you go.
For that you will have to create a seperate LocationListener outside the onCreate() and give the reference of it to the LocationManager's requestLocationUpdates like this
LocationListener mLocationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
};
And after that you will have to reference this LocationListener like this inside the onCreate()
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, mLocationListener);