Reputation: 1883
I have a separate Utility.class in my Android app and on this Utility.class I have setup a method that receives Activity and returns the stuff that I saved in SharedPreferences, like so:
public static long retrieveFromSharedPrefs(Activity activity) {
sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
long startTime = sharedPref.getLong("StartTime", 0);
return startTime;
}
The problem with this, is that when I try to access this method from a different class, I am not able to send this method the current activity:
alreadyStartTime = Utilities.retrieveFromSharedPrefs(getActivity());
The problem is that getActivity() does not appear to be a valid API method, so I have no idea what to write there, the only API method he agrees to accept there is getParent() which has no effect at all (I'm not using fragments so it's not a child activity).
I will appreciate any help, thanks a lot!! :)
Upvotes: 0
Views: 427
Reputation: 48242
You can access your shared preferences stuff from anywhere in an uniformed way:
PreferenceManager.getDefaultSharedPreferences(context)
just passing your current context
If you wish to access them from your own class you can use Application Context as an argument.
If you create your own application-derived class and register it in your Manifest you will be able to create getSharedPreference function you can use from everywhere
class MyApp extends Application {
private static MyApp instance;
public void onCreate() { this.instance = this; }
public static SharedPreferences prefs() { return PreferenceManager.getDefaultSharedPrefercnes(instance); }
}
But don't forget to include it into manifest in this case
Upvotes: 1
Reputation: 4284
Actually you are not getting the activity in this function but the Activity's Context
The best practice for getting Context
in a non-Activty
class is using a ContextWrapper
Class
please check the following link ...you'll get a clear idea, how it's work
http://itekblog.com/android-context-in-non-activity-class/
Upvotes: 0