简体   繁体   中英

how to persist data in editText using Shared Preferences in android

I have simple editText in which user enters number or string. I want to persist that number or string when user again enters the app.

1.first save this into preference like this

 SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
        prefsEditor.putString(MY_NAME, edittext.getText().toString());
        prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
        prefsEditor.commit();

2.Now second time you will get through whenever you get use this

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        String prefName = myPrefs.getString(MY_NAME, 0);
        String wallPaper = myPrefs.getString(MY_WALLPAPER, null);

It looks like you could do something similar to this: Counting Chars in EditText Changed Listener

Then, once you have detected that the text has changed, you can save it to your SharedPreferences .

Alternatively, if you only want to persist when the user leaves/enters the app, then you could just override the onPause() method of your Activity to save to your SharedPreferences . Just use <EditText>.getText() to get the String entered and then save that. Override onResume() and then use <EditText>.setText(<String from SharedPreference>) to restore it upon entering your app.

I'm assuming you know how to use SharedPreferences, but let me know if you don't.

This code will persist the data when the user removes focus from the EditText Box using the OnFocusChangeListener;

EditText userInput = (EditText)findViewById(R.id.ID_HERE);
SharedPreferences pref = this.getPreferences(this.MODE_PRIVATE);

String data_key = "data";

View.OnFocusChangeListener persistData = new View.OnFocusChangeListener(){

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // TODO Auto-generated method stub
        if(!hasFocus){
            EditText e = (EditText)v;
            SharedPreferences.Editor edit = pref.edit();
            edit.putString(data_key,e.getText().toString());
            edit.commit();
        }
    }

};

userInput.setOnFocusChangeListener(persistData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM