My app has an Activity class called MainActivity and one of its members is
public static SharedPreferences prefsdefault;
My app has also a service (in another process) which runs in background. Inside the service I wrote
MainActivity.prefsdefault.getString(Key,"Hello");
The app sometimes throws null pointer exception at this line. Why? Does it mean that this member is cleaned up by the garbage collector when I close the activity and I cannot access it at anytime (when my service runs)? So what is the perfect solution for this?
Should I pass the MainActiviy.class to the service? It also happens when I implement a thread that requires a context.
The reason for this is
SharedPreferences
is not initialised u dont need to do like this asSharedPreferences
are global available with in app if MODE is Private just create new instance in service as well it will workThat's because, even if your prefsdefault may have been initialized once, your whole app can be garbage collected and restarted again.
In that case your service will find that field as null. Using static fields inside activities is wrong for a bunch of reasons, the most important is that your app may be killed and restarted by the operating system and after that all the static fields are wiped out again.
The correct way to use shared preferences is to access them using getSharedPreferences whenever you need to access / write.
The other weird thing is that you say that the service runs in another process. In that case it should not be able to access to data from another process.
Because
prefsdefault
isNULL
. I don't see that it is initialized. You can do that byHot tip: Never make your
SharedPreference
instance static.