Using Activity class static members in a backgroun

2019-09-14 00:02发布

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.

3条回答
▲ chillily
2楼-- · 2019-09-14 00:30

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

查看更多
祖国的老花朵
3楼-- · 2019-09-14 00:39

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.

查看更多
小情绪 Triste *
4楼-- · 2019-09-14 00:44

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.

查看更多
登录 后发表回答