Can't call method in onCreate() - android

There is a problem on my Android app. If I put a method inside onCreate(), the whole app will crash.
Here is the code
private LocationManager locationManager = null;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, police.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
locationManager = (LocationManager)mainMenu.this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000 , 0 , new MyLocationUpdater());
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
updateWithNewLocation(location);
}
The updateWIthNewLocation(Location location) method is outside the onCreate();
I can't call it successfully inside the onCreate().
Any ideas?

First, you need to learn to use adb logcat, DDMS, or the DDMS perspective in Eclipse, to examine LogCat and look at the stack trace associated with your error.
My guess is that you are crashing with a NullPointerException, because location is probably null. It may take seconds to minutes before you will have a location after calling requestLocationUpdates(). If this indeed is what you are encountering, modify your application to remove the getLastKnownLocation() call and move your updateWithNewLocation() call to the onLocationChange() method in MyLocationUpdater.

Related

Android Location Services - LocationListener does not work

OLD QUESTION:
I'm trying to get my device's location coordinates and I've followed all the steps that I've found in multiple areas while researching. I've set up a LocationManager and used the requestLocationUpdates function that is tied to a LocationListener. However, the LocationListener does not respond. I've tried debugging as well as walking around outside in order for the onChangedLocation function to execute but nothing happens. In debugging the requestLocationUpdates function for my LocationManager is executed but the LocationListener is never executed.
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
locationListener = new myLocationListener();
textView.setText("Longitude", TextView.BufferType.NORMAL);
textView2.setText("Latitude", TextView.BufferType.NORMAL);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
requestLocationUpdates
Above is the use of the requestLocationUpdates function.
private class myLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
//Log.e("Latitude: ", "" + location.getLatitude());
//Log.e("Longitude: ", "" + location.getLongitude());
if(location != null)
{
textView.setText(Double.toString(location.getLongitude()), TextView.BufferType.NORMAL);
textView2.setText(Double.toString(location.getLatitude()), TextView.BufferType.NORMAL);
}
else
{
textView.setText("No Location", TextView.BufferType.NORMAL);
textView2.setText("No Location", TextView.BufferType.NORMAL);
}
Toast.makeText(getApplicationContext(),"onLocationChanged Success",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
myLocationListener
This is myLocationListener that implements LocationListener. I've added a little bit of extra code for testing purposes. The toast would never pop up so it appears as though this code is never executed. If anyone could help me out with this I would really appreciate it.
Thank you!
NEW QUESTION:
After continuing on developing in this page while waiting for a response I noticed that it takes about a minute for the location services to actually begin working. So, now my question is: how do I overcome the obstacle of a user having to wait to use the app? I've seen apps that use location based content and it does not take that long. I know that there is the getLastKnownLocation function but what if a user travels 50 miles before opening the app again? Any help on this would be appreciated. Thank you!
Each device which makes location request for gps, has to wait until gps hardware become warm. The wait time changes by device and where you stay. If you are inside a building, this time could take 1 minute or more.
To avoid wait, you can use getLastKnownLocation method, if returns a cached location, check location's date via getTime method. Determine yourself, is it old location by your scenario ?
if it's too old location, you have to make location request and wait.

Making Sure All tasks executes in onLocationChanged Method

I am doing a lot of job in onLocationChanged method, i want to lock the method until all jobs are done even if the location manager achieves it's condition.
for example i have the following code:
private LocationManager _locMgr;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
_locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 2, this);
}
public void onLocationChanged(Location location) {
//do alot of job
}
The problem i am facing that if the time in locationManager is greater than 2 seconds and greater than 2 meters it'll execute the onLocationChanged() even if there's tasks not finished.
Please somebody help me with this.
If you are sure that onLocationChanged() is called before finished, try this:
Declare an Activity field private bolean isAllDone = true;
Declare a lock object private final Object lock = new Object();
Then at onLocationChange test it:
public void onLocationChanged(Location location) {
if(isAllDone){
synchronized (lock){
if(isAllDone){
isAllDone = false;
//do alot of job
isAllDone = true;
}
}
}
}

The locationListener is only invoked once

I want to send some data along with coordinates to a remote server each 10 seconds. I thought, that the best match would be the
public void onCreate( Bundle savedInstanceState ) {
//snip
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 10000, 0, new SendingLocationListener() );
}
in the listener I have the following code:
public void onLocationChanged( Location location ) {
if( null == location ) return;
TrackerNotifierTask task = new TrackerNotifierTask();
task.execute( location );
}
the TrackerNotifierTask uses the httpclient in it's doInBackground() method, so it's pretty simple.
Now, if I start the activity, I can see that the onLocationChanged() gets executed and the data hits the remote server successfully. But only once! No matter what I do later, changing coords or anything, the task does not get called.
Is this the right way of implementing such thing in android or shall I resort to some background-service?
the link from Shrikant gave me some hints on class-structure of the LocationListener implementation.
The class must not necessarily be defined as an inner anonymous class. I defined it as inner, but named one and it also worked.
The trick is, that the listener instance must be declared as a field:
private LocationListener listener;
#Override
public void onCreate( Bundle savedInstanceState ) {
//snip
locationManager = (LocationManager)this.getSystemService( Context.LOCATION_SERVICE );
listener = new MyLocationListener( SomeActivity.this );
locationManager.requestLocationUpdates( provider, 1000, 0, listener );
}
Otherwise it will be garbage-collected after the 1st run, if defined like this:
locationManager.requestLocationUpdates( provider, 1000, 0, new MyLocationListener() );
That was one half of the solution. The other part - about minTime - remains unresolved. Maybe it has something to do with emulator... I'll post the missing part as soon as I find the way.
UPDATE:
Seems like, that on a real device the minInterval seems to cause the listener to fire, no matter if the coords changed or not
Please see this.
It works as expected when LocationListener is implemented as an anonymous class.
I'v a similar problem,
when I use
private LocationListener mLocationListener1 = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
}
in my class,
onLocationChanged is only invoked once,
but after I add "final" to
private final LocationListener mLocationListener1 = new LocationListener() {
The problem is solved. (in my case, used by forground service)
It seems like
if the variable is not defined with final keyword,
after it was called once ,
it would be garbage collected and will not be called again...

Android lastKnownLocation returns null

I've got this problem I don't see anything wrong in the code but getLastKnownLocation returns null every time . any ideas ?
public class LocationDemo2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText et1 = (EditText) findViewById(R.id.editText1);
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) et1.setText((int)location.getLatitude());
else et1.setText("null");
}
}
thanks
getLastKnownLocation() will frequently return null, particularly if the location provider (e.g., GPS) has not been used recently. You only use getLastKnownLocation() in situations where you either do not really need a location (but would like to have one) or where you will use other techniques if getLastKnownLocation() returns null (e.g., request location updates).

lm.removeUpdate(ll); not releasing updates

I have been working for 2 days looking for this bug. I have searched stackoverflow and Android documentation with no luck.
My onLocationChanged code has a counter in it that counts how many times it has been called and if I back arrow out of the activity screen on the phone and return, the counter will go up by 2 for each update. If I back arrowing out and update the GPS, the counter records that onLocationChanged is still getting called even though the screen is in the background and onPause has been called. If I go in and out of the activity with the backarrow, I can get more than two updates per GPS input send depending on how many times the activity screen is entered.
All the GPS code works but these multiple instances can't be good and they mess up other things I am trying to do, like distance traveled between two updates.
Here is what I think is the relevant parts of my code. Obviously I left out the main part but the point is that after returning to this screen after back-arrowing out then a single send of a GPS data point increments the n variable by more than one depending on how many times I have returned to the screen.
I must be doing something obvious but I can't find it.
public class Data extends Activity {
protected LocationListener ll;
protected LocationManager lm;
static int n = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
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){
n = n + 1;
textData.setText("\n" + n);
}
}
and
#Override
protected void onPause() {
if(lm != null) {
lm.removeUpdates(ll);
}
ll = null;
lm = null;
super.onPause();
}
The only clue I have is that if I take the lm.removeUpdates(ll) out of the if(lm != null) then the code crashes which makes me think that lm must be null and that lm.removeUpdates(ll) must not be correct but it matches the all the examples I could find as well as the Android documentation as far as I can tell.
Please help.
LocationListener ll = new mylocationlistener();
This LocationListener is local to your method onCreate().So is your LocationManager lm.So when you are removing updates its not working with the manager and listener that you declared as the class variable.
Just write as
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener(); in your onCreate().

Categories

Resources