我在android studio中编写了一个android应用程序。我的ProfileView类扩展了activity_profile_view.xml活动,允许用户更改其名称和描述。但每次调用onCreate或onResume方法时,都会显示默认值。没有显示应该保存在onClick或onPause中的值。谢谢,这是我第一篇文章。SharedPreferences没有保存,只有默认值
public class ProfileView extends Activity implements View.OnClickListener{
public EditText NameEdit, AboutEdit;
public Button SaveButton;
public ImageButton NewPic;
public static final String Profile_Prefs = "Pro_File";
public static SharedPreferences profile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
NameEdit = (EditText) findViewById(R.id.NameEdit);
AboutEdit = (EditText) findViewById(R.id.AboutEdit);
SaveButton = (Button) findViewById(R.id.SaveButton);
SaveButton.setOnClickListener(this);
//Restore Preferences
profile = this.getSharedPreferences(Profile_Prefs, 0);
AboutEdit.setText(profile.getString("about", "About Me"));
NameEdit.setText(profile.getString("name","name"));
}
@Override
public void onClick(View v) {
SharedPreferences profile = getSharedPreferences(Profile_Prefs, 0);
SharedPreferences.Editor editor = profile.edit();
editor.putString(NameEdit.toString(),"name");
editor.putString(AboutEdit.toString(),"about");
editor.apply();
Intent mainIntent = new Intent(this, Main.class);
startActivity(mainIntent);
};
@Override
protected void onPause(){
super.onPause();
SharedPreferences profile = getSharedPreferences(Profile_Prefs, 0);
SharedPreferences.Editor editor = profile.edit();
editor.putString(NameEdit.toString(),"name");
editor.putString(AboutEdit.toString(),"about");
editor.commit();
}
@Override()
protected void onResume(){
super.onResume();
profile = this.getSharedPreferences(Profile_Prefs, 0);
AboutEdit.setText(profile.getString("about", "About Me"));
NameEdit.setText(profile.getString("name","name"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.profile_view, menu);
return true;
}
固定的onClick和的onPause之后我得到了在应用中EDITTEXT领域休耕时的onResume或的onCreate被调用。
android.widget.EditText {1a0ea60cVFED..CL.F ...... 32,263736,426#7f0a0003应用程式:ID/NameEdit} android.widget.EditText {651555eVFED..CL .. ...... 92456-676,796#7f0a0009应用:ID/AboutEdit}
我想帮助,但现在我有新的反馈我不不明白。我用新信息更新了我的问题。 – Bishop 2014-11-23 20:01:08
对不起,我忘了添加'NameEdit.getText()。toString()'。看到我编辑的答案 – Fumarja 2014-11-23 20:04:16