【发布时间】:2014-05-03 13:20:35
【问题描述】:
我在片段中设置了一个共享首选项值。但是当我尝试在主要活动中访问该值时,我总是得到默认值;(请告诉我为什么......
在片段中:
reader= this.getActivity().getSharedPreferences("pref",0); // this is in onCreate
//this part within a onClick
editor = reader.edit();
editor.putBoolean(Preferences.passwordOn, true);
editor.putString(Preferences.password, editTextPassword.getText().toString());
editor.commit();
在主要活动中:
boolean passwordOn = reader.getBoolean(Preferences.passwordOn, false);
if(passwordOn)
{
Intent loginIntent=new Intent("com.sdg.etspandroidtracker.LOGIN");
startActivity(loginIntent);
}
更新:我的代码太乱太庞大了。 :( 所以我会告诉你那里发生了什么。
在主要活动中,首先我检查是否为应用程序设置了密码。如果是这样,我将在第二个代码部分中显示登录屏幕并结束主要活动。否则,我只保留主要活动。
在设置中,我有一个开关密码。当我打开开关时,会显示一个片段,您可以在其中输入新密码和密码确认。如果所有详细信息都正确,则密码和密码状态(设置密码时的信息)将保存在共享首选项中。这段代码是我上面给出的第一个代码部分。
我可以成功运行应用程序,并设置密码。但是当我再次运行应用程序时,不会显示登录屏幕。我调试并发现这是因为 sharedpreference 为空并给出默认值“false”,即使我上次运行应用程序时设置了密码。似乎我无法在主要活动中访问我在片段中设置的共享首选项? :\
【问题讨论】:
标签: android android-activity fragment sharedpreferences