Reputation: 487
I have an app which uses Google Maps and GPScoordinates. I need the current location in multiple classes, and i don't want to use intent.putExtra and getExtra everytime. Can I make a certain value visible to all classes in my app?
Upvotes: 0
Views: 177
Reputation: 549
There are a number of ways to do this, SharedPreferences is one but I think the best mechanism would be to use a global context. You do this by overriding Application with a custom class.
public class GlobalContext extends Application{
private String mSomething;
public String getSomething() {
return mSomething;
}
public void setSomething(String value) {
mSomething = value;
}
That is then used in your manifest
<application
android:name="com.example.GlobalContext"
...
Then in all of your activities a call to getApplicationContext will return the instance of that class.
final GlobalContext globalContext = (GlobalContext) getApplicationContext();
Upvotes: 1
Reputation: 782
Can't say this answer is better than the answers posted above, but why not use a Singleton class?
eg
public class GPSValues{
public static GPSValues INSTANCE = new GPSValues();
protected double lat, lon, alt;
public static GPSValues getInstance(){
return INSTANCE;
}
public double getLat(){
return lat;
}
.
.
.
}
Then to use it, just do GPSValues.getInstance().setLat(number) and double lat = GPSValues.getInstance().lat
Upvotes: 1
Reputation: 921
I think a very "hacky" way to go about it is just make the information you want to share public. Then access it from another activity, such as var coordinates = MainActivity.GPScoordinates
This isn't the best approach, but its certainly simple.
Upvotes: 0