我的应用程序中有两个活动现在我想保存editText的文本,当用户转到下一个时,由用户给出,在返回到MainActivity之后,该值应放在editText中,我的代码是
public class MainActivity extends Activity {
EditText editText;
String name = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
if(savedInstanceState == null){
editText.setText("Some Thing");
}else{
String newValue = savedInstanceState.getString("myData");
editText.setText(newValue);
}
Log.d("ARSHAY....", "in onCreate()");
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(savedInstanceState);
editText = (EditText) findViewById(R.id.editText1);
name = editText.getText().toString();
savedInstanceState.putString("myData", name);
}
public void goToNextArsh(View view ) {
Intent intent = new Intent(MainActivity.this, Second.class);
startActivity(intent);
}
}
但是这并没有将新输入设置为返回MainActivity。 有没有人知道怎么做?
答案 0 :(得分:1)
首先,为什么两次使用editText = (EditText) findViewById(R.id.editText1);
?
仅在onCreate()
并使用此代码
@Override
protected void onPause() {
SharedPreferences pref = getSharedPreferences("YOUR_KEY", MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("som.arshay.retreive.data", editText.getText().toString());
edit.commit();
super.onPause();
}
@Override
protected void onResume() {
SharedPreferences pref = getSharedPreferences("YOUR_KEY", MODE_PRIVATE);
String newValue = pref.getString("som.arshay.retreive.data", "");
editText.setText(newValue);
super.onResume();
}
答案 1 :(得分:0)
使用这些方法onSaveInstanceState(Bundle outState)
和onRestoreInstanceState(Bundle savedInstanceState)