Arshad Ali
Arshad Ali

Reputation: 3274

could not be able to save date during switching between activities

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?

Upvotes: 0

Views: 119

Answers (2)

Jignesh Ansodariya
Jignesh Ansodariya

Reputation: 12695

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

Upvotes: 1

Prasanna
Prasanna

Reputation: 236

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

Upvotes: 0

Related Questions