I want my app to save textView2 in shared preferences. This is the current shared preferences code I have that saves the state of a checkbox (checked/unchecked).
private boolean getFromSP(String key){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
return bifrostPrefs.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = bifrostPrefs.edit();
editor.putBoolean(key, value);
editor.commit();
}
I never really worked with shared prefrences before so I don't really know how would I create a new shared prefrence to save my textview2.
You can't.
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.
From doc Using Shared Preferences
Al-thought you can store value of TextView
//To get stored value
private String getString(String key){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
return bifrostPrefs.getString(key, "");
}
..
//To Save value
private void saveString(String key, String value){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = bifrostPrefs.edit();
editor.putString(key, value);
editor.commit();
}
How to use these methods
Put this code where you want to save TextVIew's value
//To save value of TextView
if (!TextUtils.isEmpty(aTextView.getText())) {
saveString("aTextView", aTextView.getText().toString());
}
//To Read and show into TextVIew
aTextView.setText(getString("aTextView"));
You can easily save strings in Shared Preferences:
If you are unsure how to use Shared Preferences, this will be of great value to you.
As to TextViews, How about saving textView2.getText()
?
TextView.getText()
obviously returns the text TextView is displaying. If you need other TextView properties, consult this.
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.