我在标签中使用了sherlock片段,但我无法访问sharedpreference
或保存它,我该怎么办?这是我的代码:
public class SettingsActivity extends SherlockFragment {
private CheckBox cb1;
private Context context = getActivity();
private SharedPreferences sp;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.settings_layout, container, false);
cb1 = (CheckBox)rootView.findViewById(R.id.cb1);
sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged (CompoundButton cb, boolean isChecked) {
if (isChecked) {
context.getSharedPreferences("some_pref", Context.MODE_PRIVATE)
.edit()
.putBoolean("some_bool_name", true)
.commit();
}
}
});
return rootView;
}
}
如果上述方法无法更正,请告诉我如何保存偏好。
logcat的
11-13 18:13:36.907:I / ActivityManager(10626):START u0 {act = android.intent.action.MAIN cat = [android.intent.category.LAUNCHER] flg = 0x10200000 cmp = com.myapp来自pid 10836的.test / .MainActivity} 11-13 18:13:36.907:D / ActivityManager(10626):TopActivityInfo,pkgName:com.myapp.test activityName:com.myapp.test.MainActivity bstSpecialAppKeyboardHandlingEnabled = false 11-13 18:13:36.907:D / GuidanceScreen(10824):appName:My App,currentPkg:com.myapp.test,event:app_launch,controller:Keyboard 11-13 18:13:36.907:D / ActivityManager(10626):显示pkgName的指南:com.myapp.test 11-13 18:13:36.917:D / GuidanceScreen(10824):appName:我的应用程序 11-13 18:13:36.987:D / GuidanceScreen(10824):没有com.myapp.test的指导。 11-13 18:13:37.037:D / WindowManager(10626):使用数据发送appClickStats请求:[package = com.myapp.test,appname = My App,appver = 1.0,clickloc = system_server] 11-13 18:13:37.237:I / ActivityManager(10626):显示com.myapp.test / .MainActivity:+ 260ms 11-13 18:13:46.227:D / AndroidRuntime(15464):来自cmdline的procName:com.myapp.test 11-13 18:13:46.227:E / AndroidRuntime(15464):在writeCrashedAppName中,pkgName:com.myapp.test 11-13 18:13:46.227:D / AndroidRuntime(15464):使用内容成功编写的文件:com.myapp.test StringBuffer :; com.myapp.test 11-13 18:13:46.237:E / AndroidRuntime(15464):进程:com.myapp.test,PID:15464 11-13 18:13:46.237:E / AndroidRuntime(15464):at com.myapp.test.SettingsActivity.onCreateView(SettingsActivity.java:40) 11-13 18:13:46.267:I / ActivityManager(10626):进程com.myapp.test(pid 15464)已经死亡。 11-13 18:13:46.267:W / ActivityManager(10626):强制删除ActivityRecord {4b12da0c u0 com.myapp.test / .MainActivity t17}:app死了,没有保存状态 11-13 18:13:46.287:I / WindowState(10626):胜利死亡:窗口{4b1ac890 u0 com.myapp.test / com.myapp.test.MainActivity}
答案 0 :(得分:0)
初始化共享偏好设置:
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
在onCreateView()中:
loginPreferences = getActivity().getSharedPreferences("loginPrefs", getActivity().MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
保存:
loginPrefsEditor.putString("start_time", yourText);
loginPrefsEditor.commit();
提取:
String dateString = loginPreferences.getString("start_time", "");