I want to avoid duplicating code that needs to use methods on Activity (say getActivity().getString()) .
Creating a object that keeps a reference to an Activity does not seem to work (objects are recreated all the time, and any reference to an Activity is null when you need it.)
// This won't work, it seems
public class MyUtils {
public MyUtils(Activity activity) {
this.activity = activity;
}
public String getSomeStuff() {
return this.activity.getString(R.string.foo);
}
}
// In a Fragment created by the activity
MyUtils utils = new MyUtils(getActivity());
myUtils.getSomePref();
So how to you avoid duplicating code ? Is there a "safe" way to factor code that needs an Activity ? Should you put all the code in the Activity itself, and cast it from Fragments ?
Edit : to clarify my issue, I'm especially looking for a way to share code between Fragments, that are displayed as Tabs in an Activity (using a TabsPagerAdapter). They all need to access some structured data that is saved as a couple of preferences. They also need to access this data in an onSharedPreferencesChanged event handler, when the Fragments are not visible. In my experience, whenever I stop and resume the application, navigate between fragments, change the preferences, etc... all my variables to the activity are null.