访问另一个活动的preferences [英] Accessing another Activity's preferences

查看:251
本文介绍了访问另一个活动的preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储在其自己的共享preferences凭据登录活动;后来我加了两个干将阅读他们,像

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);
}

但是,这将引发时,我把它称为这样的NPE

but this throws a NPE when I call it like this

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

看来,一个简单的构造器调用后的活动不能读取其preferences,就好像它是在一些未完成的状态。我阅读了大量相关的话题,但没有能够找到一个解决方案。基本上,我需要在我的应用分享活动中这些凭据

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

推荐答案

这是如何创建活动不是。当你刚刚叫新登录(),它没有一个正确的上下文访问共享preferences。你应该也永远不会叫上延伸活动服务<一类/ code>。这歌Android类不是如何工作的。

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.

但它听起来像你的设计是不正确的。你不应该需要获取另一个活动的preferences。如果你这样做,只是把它放在defaultShared prefernces代替。

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.

这篇关于访问另一个活动的preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆