各位大大好:
想請教一下,我用SharedPreferences可以幫我記住頁面中的edittext的資料
但我希望這頁面所儲存的資料在其他頁面也能用,我該怎麼做?
以下是第一頁面程式碼:
public class MainActivity extends Activity {
private Button login;
private EditText acc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button)findViewById(R.id.login);
acc=(EditText)findViewById(R.id.acc);
SharedPreferences myrecord=getPreferences(Activity.MODE_PRIVATE);
String name_str=myrecord.getString("acc", "");
acc.setText(name_str);
login.setOnClickListener(getDBRecord);
}
private Button.OnClickListener getDBRecord = new Button.OnClickListener() {
public void onClick(View v) {
SharedPreferences myrecord=getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor edit=myrecord.edit();
edit.putString("acc", acc.getText().toString());
edit.commit();
}
};
}
以下是第二頁面程式碼:
public class Mymenu extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymenu);
SharedPreferences spref = getApplication().getSharedPreferences("acc", Context.MODE_PRIVATE);
String strValue = spref.getString("acc", null);
mytoast(strValue+"");
}
private void mytoast(String str)
{
Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
但怎麼印出來都是null
我在第一頁面已經確定值有被記憶了....
謝謝
getPreferences 官方文件的定義
Retrieve a SharedPreferences object for accessing preferences that are ★★★private to this activity★★★. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
幫你畫重點了
你存值是用
getPreferences
取值卻是用
getSharedPreferences
請改用 getSharedPreferences 取/存值