Actually there is a way: You would need to extend android.app.Application
class ( which also extends Context ), and in this class fill a singleton
reference to it, so the code would be something like:
MyApplication extends Application{
private static MyApplication INSTANCE;
public MyApplication getInstance(){
return INSTANCE;
}
@Override
onCreate<http://developer.android.com/reference/android/app/Application.html#onCreate%28%29>
(){
super.onCreate();
INSTANCE = this;
}
...
}
..and then, wherever You need Your Context just paste:
Context c = MyApplication.getInstance();
Of course in order for Android to see MyApplication, You'll need to mention
that in AndroidManifest.xml, in <application> tag, with field android:name
W dniu piątek, 2 listopada 2012 15:11:35 UTC+1 użytkownik Jayawant Jagtap
napisał:
>
> Hello,
>
> I want to get instance of the SharedPreferences in the class which is not
> derived from Activity or Service, Can I get it without paasing Context
> object to that class.
>
> class Helper{
> private SharedPreferences mPref = *null* ;
> private String data="";
>
> private *static* *final* String *KEY* = "key";
>
> public static void init(Context a){
> mPref= a.getSharedPreferences(*PREF_FILE*, 0);
>
> data=mPref.getString(*KEY*, *""*);
> }
>
> public string getdata{
> return data; //In this method if data is empty string
> due to init method is not called in some case,I want to call init() method
> from here.
> } //But I don't have context object. I
> can't call init before each getdata() call because there also context
> object is not available in some cases.
> } // I can store Context object as Helper
> class variable,but it is failing if first getdata() call executes before
> init() call.
>
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en