user4058730
user4058730

Reputation:

Keeping Text in Edit Text Present unless Modified

I tried searching on stackoverflow and android develoer websites, but I could not find any method/command as to how to keep the text entered by the user in the Edit Text box even when we close the activity.

What I am trying to make is that I have a an activity which takes input from user in the editText box, and when the user press the back button to go to a different acitviy and then when (s)he comes (s)he finds the text as last entered instead of the blank editText dialog box.

Apology if the question has been asked.

Upvotes: 0

Views: 43

Answers (3)

jaumard
jaumard

Reputation: 8292

You have to use sharedPreferences to do this : Save your preference like this (when activity was paused for example) :

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
prefs.edit().putString("myvalue", myEditText.getText().toString()).apply();

And restaure the value on the onCreate method of your activity :

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
myEditText.setText(prefs.getString("myvalue", ""));

You activity look like this at the end :

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, ShakeService.class));

        EditText myEditText = (EditText)findViewById(R.id.myedittext);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        myEditText.setText(prefs.getString("myvalue", ""));
    }

    @Override
    protected void onPause()
    {
        super.onPause();

        EditText myEditText = (EditText)findViewById(R.id.myedittext);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("myvalue", myEditText.getText().toString()).apply();
    }
}

Upvotes: 1

Darsh Patel
Darsh Patel

Reputation: 1015

If you want to do like this then you need to store all edittext value in preferences when onbackpress() called.

When we come again in activity then set text of edittext from preferences in onCreate() or onResume().

Upvotes: 0

Sanjeet A
Sanjeet A

Reputation: 5227

You need to save it in persistent storage. Using a SharedPreferences may be better solution.

Upvotes: 0

Related Questions