我看到以前有人问过这个问题,但是提供的答案都没有对我有用。
所以,我有两个活动:A 和 B。用户在 A 中插入了一些数据,我希望能够从 B 访问它们(以及将来的更多活动)。我正在尝试使用共享偏好来做到这一点。现在看来,我的代码能够正确地将数据保存在活动 A 中,但是我无法从活动 B 访问相同的 sharedPreference,因为对象(在活动 B 中)为空。看起来它创建了另一个具有相同名称的对象。
我对 android 和 java 很陌生,所以我知道可能只是我不明白这个类是如何工作的,我做错了什么?
活动一
SharedPreferences sharedPref = this.getSharedPreferences("PREF_PERSONAL_DATA",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.n),n);
editor.putInt(getString(R.string.hi), hi);
editor.putInt(getString(R.string.wa), wa);
editor.putInt(getString(R.string.he), he);
editor.putInt(getString(R.string.we), we);
editor.putInt(BlocksNumStr, BlocksNum);
editor.commit();
活动 B
SharedPreferences sharedPref = this.getSharedPreferences("PREF_PERSONAL_DATA", Context.MODE_PRIVATE);
String Weight = sharedPref.getString("we", null);
int W = sharedPref.getInt("weight", 0);
TextView ShowWeight = (TextView) findViewById(R.id.attempt);
ShowWeight.setText(Weight);
TextView ShowW = (TextView) findViewById(R.id.attemptW);
ShowW.setText(W);