0

我的应用程序中有两个活动现在我想保存 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 时设置新输入。有没有人知道该怎么做?

4

2 回答 2

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();
}
于 2013-02-21T05:48:22.567 回答
0

使用这些方法onSaveInstanceState(Bundle outState)onRestoreInstanceState(Bundle savedInstanceState)

于 2013-02-21T05:01:18.190 回答