问题描述
- 不同 activity 中的 SharedPreferences
- 我用下面的代码从 activity A 中加载 SharedPreferences:
private void SavePreferences(String key String value){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(key value); editor.commit(); }
在 activity B 中我想加载 SharedPreferences。下面是一个异常 NullPointerException:
private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); data = sharedPreferences.getString(""name""08:00"") ; }
我用下面的代码,得到这个编译错误:""No enclosing instance of the type A is accessible in scope""
private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this); data = sharedPreferences.getString(""name""08:00"") ; }
如何访问数据?谢谢!
解决方案
在两个 Activities 中把 this 替换为 getApplicationContext()
在Activity A 的 SharedPreferences 是下面的方式:
private void SavePreferences(String key String value){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(key value); editor.commit(); Intent sd=new Intent(thisSecongtess.class); startActivity(sd); }
Activity B 中按下面的方式获取值:
private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String data = sharedPreferences.getString(""name""08:00"") ; Toast.makeText(thisdata Toast.LENGTH_LONG).show(); }
解决方案二:
在 shared preferences 中存储值
SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor=preferences.edit(); editor.putString(""Name""Harneet""); editor.commit();
从 shared preferences 中检索值:
SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this); String name=preferences.getString(""Name"""); if(!name.equalsIgnoreCase("""")) { name=name+"" Sethi""; /* 编辑值 */ }
从 sharedpreference 中编辑数据
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putString(""text"" mSaved.getText().toString()); editor.putInt(""selection-start"" mSaved.getSelectionStart()); editor.putInt(""selection-end"" mSaved.getSelectionEnd()); editor.commit();
从 shared preference 中检索数据
SharedPreferences prefs = getPreferences(MODE_PRIVATE); String restoredText = prefs.getString(""text"" null);if (restoredText != null) { //mSaved.setText(restoredText TextView.BufferType.EDITABLE); int selectionStart = prefs.getInt(""selection-start"" -1); int selectionEnd = prefs.getInt(""selection-end"" -1); /*if (selectionStart != -1 && selectionEnd != -1) { mSaved.setSelection(selectionStart selectionEnd); }*/}
时间: 2024-08-01 16:01:14