yasserbn
yasserbn

Reputation: 391

Using Activity class static members in a background service

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.

Upvotes: 0

Views: 701

Answers (3)

fedepaol
fedepaol

Reputation: 6862

That'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.

Upvotes: 1

DjHacktorReborn
DjHacktorReborn

Reputation: 2928

The reason for this is SharedPreferences is not initialised u dont need to do like this as SharedPreferences are global available with in app if MODE is Private just create new instance in service as well it will work

Upvotes: 0

poitroae
poitroae

Reputation: 21377

Because prefsdefault is NULL. I don't see that it is initialized. You can do that by

prefsdefault = getSharedPreferences("my_preferences", Activity.MODE_PRIVATE);

Hot tip: Never make your SharedPreference instance static.

Upvotes: 0

Related Questions