我有两个不同的活动。第一个只第一次向用户显示 - 将电话号码存储在共享首选项中。我认为问题是我从 prefs 方法加载,但以防万一我会将所有内容留在这里以使其与未来的用户更相关。 看起来在这两个活动中都保存了"mobilnummer"-但是我在显示它们时遇到了问题。
这个想法是如果用户更新它就会被覆盖 - 我认为该方法会这样做吗?
启动.java
public static final String PREFS_NAME = "MobileNumberSaved";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
轮廓
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
这就是我认为的问题/问题!(下面的代码)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
我认为这是你的错误:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
但是从共享首选项中获取值的正确方法是这样的:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
更新:当您在共享首选项中保存值时,您只保存 editText,而不是它的值,因此在保存时执行以下操作:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
其他一切都和我上面写的一样