我必须使用android中的sharedpreferences类来共享首选项,并且首选项必须在两个活动之间共享.如何将这些偏好从一个活动传递到另一个活动?可以使用静态变量,但它们对我不起作用.
//code for setting shared preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("login_session_key",response.getLogin_Session_Key());
editor.putString("user_name", username.getText().toString());
editor.commit();
//code for getting shared preferences
SharedPreferences settings = getSharedPreferences(SignIn.PREFS_NAME,
Activity.MODE_PRIVATE);
username = (TextView) findViewById(R.id.username);
String uname = settings.getString("user_name", null);
username.setText(uname);
Run Code Online (Sandbox Code Playgroud)
Bil*_*ote 94
您应该通过意向调用将它们传递给活动,或者您应该阅读新活动中需要的活动.
创建一个帮助程序类,处理所有活动的所有共享首选项调用.然后在需要存储/获取首选项的任何活动上实例化它的实例.
public class AppPreferences {
public static final String KEY_PREFS_SMS_BODY = "sms_body";
private static final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); // Name of the file -.xml
private SharedPreferences _sharedPrefs;
private Editor _prefsEditor;
public AppPreferences(Context context) {
this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this._prefsEditor = _sharedPrefs.edit();
}
public String getSmsBody() {
return _sharedPrefs.getString(KEY_PREFS_SMS_BODY, "");
}
public void saveSmsBody(String text) {
_prefsEditor.putString(KEY_PREFS_SMS_BODY, text);
_prefsEditor.commit();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的活动......
public class MyActivity extends Activity {
private AppPreferences _appPrefs;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_appPrefs = new AppPreferences(getApplicationContext());
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
和
String someString = _appPrefs.getSmsBody();
Run Code Online (Sandbox Code Playgroud)
要么
_appPrefs.saveSmsBody(someString);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72652 次 |
| 最近记录: |