質問

I have two activities in my app now I want to save text of the editText, when user goes to next, which is given by the user and after coming back to MainActivity that value should be placed in editText my code is

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);
}
  }

but this does not set the new input on coming back to the MainActivity. does any body know how to do that?

役に立ちましたか?

解決

first of all why are you using editText = (EditText) findViewById(R.id.editText1); two times. use only in onCreate()

and use this code

@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();
}

他のヒント

Use these methods onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top