如何在SharedPreferences中保存TextView值,请参阅下面的代码,让我知道如何存储到SharedPreferences并在onCreate中检索(..)
我的代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(strEventName);
txtOperative.setText(strOperativeName);
}
无论何时用户返回此活动,我都希望在TextView中始终显示这些值
答案 0 :(得分:6)
简单地使用它来保存共享首选项中的TextView值
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtEvent.getText().toString());
sedt.putString("txtopertaive", txtOperative.getText().toString());
sedt.commit();
之后,通过
在Activity类或任何其他Activity中的任意位置检索它 SharedPreferences sp = getSharedPreferences("key", 0);
String tValue = sp.getString("textvalue","");
String tOperative = sp.getString("txtopertaive","");
答案 1 :(得分:1)
要保存数据,看不到SharedPreferences
的任何来电 - editor
/ editor.commit()
将这些功能添加到您的活动中:
当您想保存数据时:
saveDataToPreferences(context, "strEventName", valueHere);
在你的活动中,
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context=this;
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(getDataFromPreferences(context,"strEventName"));
txtOperative.setText(getDataFromPreferences(context,"strEventName"));
}
public static void saveDataToPreferences(Context context, String key,
String value) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDataFromPreferences(Context context, String key) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
return prefs.getString(key, Constants.BLANK);
}
答案 2 :(得分:0)
要存储在共享首选项中,您的值将使用该代码。
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("OPERATIVE", txtOperative.getText().toString());
editor.String("EVENT", txtEvent.getText().toString());
editor.commit();
答案 3 :(得分:0)
使用
prefs.edit().putString(context.getString(R.string.NAME), name).commit();
为了将数据保存到共享首选项和
prefs.getString(context.getString(R.string.NAME), "");
从共享偏好设置中获取数据。
答案 4 :(得分:0)
定义如下的编辑
private Editor editor;
并在初始化共享首选项后初始化它,如
editor = prefs.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.commit();
要检索此值,只需调用
即可String value = prefs.getString("key1","");