编辑:对不起,我最初读错了问题
我可以在可执行文件中使用 SharedPreferences 吗?
是的。如果数据是原始类型,您绝对应该这样做。
怎么做?
来自安卓开发者documentation:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
我发布了关于如何使用 SharedPrefs here 的类似答案,请注意,SharedPreferences 的这个用例打破 HashMap 的好处,它非常快速地查找和获取值一把钥匙。
您可以这样做的一种方法是:
//if you are running the code inside from an Activity
Context context = this;
SharedPreferences userSharedPrefs = context.getSharedPreferences("USER_NAME_PREFS", MODE_PRIVATE);
SharedPreferences pwdSharedPrefs = context.getSharedPreferences("PWD_PREFS", MODE_PRIVATE);
getAll() 方法将返回一个名为HashMap 的数据结构,其工作方式类似于字典:
对于存储的每个值,都有一个唯一键。
旁注:一次性获取它们有点破坏了这个数据结构的目的,但让我们继续
Map<String, String> userNameHashMap = (Map<String, String>)userSharedPrefs.getAll();
Map<String, String> pwdHashMap = (Map<String, String>)pwdSharedPrefs.getAll();
然后你可以对他们做任何你想做的事
希望它们在列表中? (我假设你的用户名是字符串)
List<String> userNameList = new LinkedList<>();
userNameList.addAll(userNameHashMap.values());
想知道用户 john 是否有密码?
boolean johnHasPasswd = pwdHashMap.containsKey("john");
String johnsPass;
if(johnHasPasswd)
johnsPass = pwdHashMap.get("john");
如果你想使用原生的数据存储机制,你受限于以下
您的数据存储选项如下:
你应该看看这些来自开发者网站的official docs。
希望这会有所帮助!