I have 2 activites (one with listview and 1 with mapview). Both activities have refresh button that fetches location and then downloads some data from the internet. I have duplicate code for location and data fetch in both activities.
How to have this code just in 1 place and to be able to call it from any activity? Can i put it in Application object?
Create a class for example GPSGetter which keeps getting the coordinates from the GPS, Then instantiate via createInstance() method of that class, in the onCreate method of your main activity. Then define a getInstance() method in that class.
For example
class GPSGetter {
GPSGetter obj;
//constructor
private GPSGetter(){
//do some stuff here
}
public GPSGetter createInstance(){
if(obj == null)
obj = new GPSGetter();
}
public getGPSGetter(){
return obj;
}
In this manner you can call getInstance from both of your Activity classes and do not need to worry about duplication, also this will make sure only one object of class is created.