Newb question: Using the same object over two methods?
Hi guys,
I'm a bit of a newbie to Java and was wondering if someone here may be able to help.
I've had a few tries at typing out an explanation of what I mean and failed miserably so I will post the code
Code java:
*/
public void onLocationChanged(Location location) {
//Some non relevant code removed//
SharedPreferences app_preferences_write = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor e = app_preferences_write.edit();
String latString = Double.toString(lat);
String lngString = Double.toString(lng);
e.putString("latitude", latString);
e.putString("longitude", lngString);
}
public void savePosition() {
e.commit();
}
My problem is that my object 'e' cannot be seen from savePosition() and I cannot commit in the onLocationChanged method as this would save the position every single time a new position is recorded.
Please can someone offer some advice?
Re: Newb question: Using the same object over two methods?
Quote:
my object 'e' cannot be seen from savePosition()
You need to move the definition of e to put it in scope for the savePosition() method.
Re: Newb question: Using the same object over two methods?
Thanks for the response but I'm still not sure I understand.
I define 'e' in the onLocationChanged method and then use e.putString to 'save' it to the object. If I define 'e' again in savePosition() won't that create a new object and therefore not have the data available to save when using e.commit()?
Re: Newb question: Using the same object over two methods?
Quote:
If I define 'e' again in savePosition() won't that create a new object
Yes every time you define a variable in its own scope, a new object will be created.
Quote:
therefore not have the data available to save when using e.commit()?
If the e.commit() call uses a different object than the one with the data, then the data won't be there.
The same variable e should be in scope for the two methods that use it.
Right now the first e is local to the first method.
Re: Newb question: Using the same object over two methods?
Wow, thanks for the fast response.
Okay, sorry if I sound ignorant but if every time I define 'e' to be able to access it within different methods then really what my question should be is, what is the best way of passing or reading the lngString and latString variables from onLocationChanged?
I've tried moving the entire 'e' object into the savePosition() method and then defining the strings as 'final' thought I am still unable to read them.
Re: Newb question: Using the same object over two methods?
Quote:
define 'e' to be able to access it within different methods
Make e a class variable. Then all methods can see it.
Recommendation: Change the name to a meaningful one vs a single letter.