Accessing another Activity's preferences

一世执手 提交于 2020-01-17 13:41:45

问题


I have a Login Activity which stores credentials in its own SharedPreferences; then I added two getters for reading them, something like

public String getUsername() {
  return getPreferences(MODE_PRIVATE).getString("#username", null);
}

but this throws a NPE when I call it like this

String mUser = (new Login()).getUsername();

It seems that the Activity cannot read its preferences after a simple contructor call, as if it were in some uncompleted state. I read lots of related topics, but wasn't able to find a solution. Basically, I need to share these credentials among activities in my application


回答1:


That's not how you create Activities. When you just call new Login(), it doesn't have a correct context to access the shared preferences. You should also NEVER, EVER call new on a class that extends Activity or Service. That's not how android classes work.

You'll need a way to get a reference to the Activity.

But it sounds like your design isn't correct. You shouldn't need to get at another activity's preferences. If you do, just put it in the defaultSharedPrefernces instead.



来源:https://stackoverflow.com/questions/4619724/accessing-another-activitys-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!