> I have some shared preferences (user_id, email) that I want to access
> from services and classes that are not subclassed from Activity.  I
> have been trying to implement this today and keep hitting roadblocks.
>
> In particular, when I try to access getSharedPreferences, I get a null
> pointer exception.  My code is posted below
>
> My goal here is to allow read access the shared preferences to objects
> and (potentially) services that aren't going to be directly exposed to
> the user.  Any suggestions/examples that can help me along?
>
>
> Many thanks,
>
> Brooke
>
> <snip>
> public class MyPrefs extends Service {
>     public static final String PREFS_NAME = "MyPrefs";
>     private int user_id;
>     private String user_email;
>     private String user_password;
>     private Editor editor = null;
>
>     private SharedPreferences settings = null;
>
>
>     public MyPrefs () {
>
>         settings = this.getSharedPreferences(PREFS_NAME,
> Context.MODE_PRIVATE);
>     }
>
> </snip>
>
> the this.getSharedPreferences line causes a null pointer exception.

First, do not implement a constructor. Move your code into onCreate() in
your service. Activities, services, etc. should not implement
constructors, or if they do, they should not expect Android API methods to
work from those constructors.

Second, if for some reason you do implement a constructor, please chain to
the superclass.

Third, I would switch to PreferenceManager.getDefaultSharedPreferences(),
particularly if you intend to use the preference API (PreferenceScreen) to
collect the preferences.

-- 
Mark Murphy (a Commons Guy)
http://commonsware.com
Android App Developer Books: http://commonsware.com/books.html



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to