cho*_*bo2 16 android sharedpreferences
我正在寻找一个Android共享首选项,我想知道有没有办法只检查首选项文件是否存在.
SharedPreferences mySharedPreferences ;
mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode);
Run Code Online (Sandbox Code Playgroud)
上面的代码让我相信"Name_of_Your_preferene"存储为一个文件或某种包含您的首选项的容器.
我想知道是否在那里检查是否存在.当用户加载活动时,我想将所有设置保存到此文件中,并带有一些默认值(所有设置均为关闭).但是,如果他们第一次访问该页面,我只想这样做.
否则,如果每次页面加载时我都会这样做
SharedPreferences.Editor editor= mySharedPreferences.edit();
/* now store your primitive type values. In this case it is true, 1f and Hello! World */
editor.putBolean(“myBoolean”,true);
editor.putFloat(“myFloat”,1f);
editor.putString(“myString”,” Hello! World”);
Run Code Online (Sandbox Code Playgroud)
我猜它会覆盖他们设置的所有设置.
Fin*_*rit 22
SharedPreferences保存在xml文件中.您可以在/data/data/your_application_package/shared_prefs/Name_of_your_preference.xml中找到它
要检查SharedPreferences的"Name_of_your_preference"是否存在:
File f = new File(
"/data/data/your_application_package/shared_prefs/Name_of_your_preference.xml");
if (f.exists())
Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
else
Log.d("TAG", "Setup default preferences");
Run Code Online (Sandbox Code Playgroud)
问候.
小智 5
我没有足够的代表来评论natur3的帖子。因此这个答案。
@ natur3:非常有帮助,谢谢。但是,我有一个小问题...文件后缀。如果我这样定义我的文件名:
private static final String FILENAME = "myPrefs";
Run Code Online (Sandbox Code Playgroud)
然后使用:
File f = new File("/data/data/" + getPackageName() + "/shared_prefs/" + FILENAME);
Run Code Online (Sandbox Code Playgroud)
即使文件存在于文件系统中,f.exists()也会返回false。这是因为Android在编写SharedPreferences时会自动添加“ .xml”后缀,因此我必须使文件引用看起来像这样:
File f = new File("/data/data/" + getPackageName() + "/shared_prefs/" + FILENAME + ".xml");
Run Code Online (Sandbox Code Playgroud)
为它工作。我不知道您从何处获得“ _preferences.xml”后缀。
我设法通过使用Window-> Show View-> Other ...在Eclipse中浏览模拟器文件系统,然后选择“ File Explorer”来解决这个问题。