Android的共享preferences例子 [英] Android Shared preferences example
问题描述
我一直在寻找网上一个很好的例子,但我不能找到一个。 我想检索用户输入以供以后使用的应用程序。
例如,用户被提示输入所有7个星期几和类型分为EDITTEXT盒子星期一,星期二等,然后在后面的应用程序中的问题上来了,问什么是你最喜欢的一天?和微调将展示他们的回升,从用户输入的天的下拉列表。
我猜测共享preferences将工作,但我不能找到一个很好的例子,给我一个首发位置。任何帮助将是AP preciated。
在preference设定值:
// MY_ preFS_NAME - 就像一个静态的字符串变量:
//公共静态最后弦乐MY_ preFS_NAME =我的prefsFile;
共享preferences.Editor编辑= getShared preferences(MY_ preFS_NAME,MODE_PRIVATE).edit();
editor.putString(姓名,埃琳娜);
editor.putInt(idName,12);
editor.commit();
从preference数据:
共享preferences preFS = getShared preferences(MY_ preFS_NAME,MODE_PRIVATE);
字符串restoredText = prefs.getString(文字,NULL);
如果(restoredText!= NULL){
字符串名称= prefs.getString(没有名字定义,名); //没有定义名称为默认值。
INT idName = prefs.getInt(idName,0); // 0为默认值。
}
详细信息:
I have been looking online for a good example but I can not find one. I want to retrieve user input in an app for later use.
For example, the user is prompted to enter all 7 days of the week and types into the editText box "Monday", "Tuesday" etc. Then later in the app a question will come up and ask what is your favorite day? and the spinner will show a dropdown list of the days they entered for the user to pick from.
I am guessing shared preferences would work for this, but I can not find a good example to give me a starting place. Any help would be appreciated.
Setting values in Preference:
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
more info:
这篇关于Android的共享preferences例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!