How To Persist Data In Edittext Using Shared Preferences In Android
Solution 1:
1.first save this into preference
like this
SharedPreferencesmyPrefs=this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.EditorprefsEditor= 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
SharedPreferencesmyPrefs=this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
StringprefName= myPrefs.getString(MY_NAME, 0);
StringwallPaper= myPrefs.getString(MY_WALLPAPER, null);
Solution 2:
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.
Solution 3:
This code will persist the data when the user removes focus from the EditText Box using the OnFocusChangeListener;
EditTextuserInput= (EditText)findViewById(R.id.ID_HERE);
SharedPreferencespref=this.getPreferences(this.MODE_PRIVATE);
Stringdata_key="data";
View.OnFocusChangeListenerpersistData=newView.OnFocusChangeListener(){
@OverridepublicvoidonFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stubif(!hasFocus){
EditTexte= (EditText)v;
SharedPreferences.Editoredit= pref.edit();
edit.putString(data_key,e.getText().toString());
edit.commit();
}
}
};
userInput.setOnFocusChangeListener(persistData);
Post a Comment for "How To Persist Data In Edittext Using Shared Preferences In Android"