如何创建、读取和写入共享的首选项文件



我有一个语音录制应用程序,可以录制语音并将其保存到WAV文件中。在命名文件时,我希望能够将其命名为Recording X.wav,其中X被一个数字取代。我想存储一个计数器,用来计算已经创建了多少个文件,所以当录制完成时,它会在计数器上添加一个。很多SO帖子建议使用共享偏好文件,但我在项目目录中的任何地方都找不到它——我的共享偏好文件。我如何创建一个,读它并写它?

(附言:我是安卓工作室的初学者,所以你能试着帮我把答案弄清楚吗?(

您可以在项目中创建SharedPreferences,而无需在项目目录中找到它。创建后,它实际上存储在应用程序文件系统中的项目文件夹中(/data/data/your_PACKAGE_NAME/shared_prefs/your_prefs_NAME.xml(。但对于创建、更新和检索,您不想去那里。

创建SharedPreference

SharedPreferences.Editor editor = getSharedPreferences("MyPreference", MODE_PRIVATE).edit();
editor.putString("name", "Nathan");
editor.putInt("id", 1000);
editor.apply();

检索

SharedPreferences prefs = getSharedPreferences("MyPreference", MODE_PRIVATE); 
String name = prefs.getString("name", "Blank Name"); //"Blank Name" the default value.
int idName = prefs.getInt("id", 0); // 0 is the default value.

请通过以下链接了解更多详细信息。https://developer.android.com/reference/android/content/SharedPreferences?hl=en

public class Pref {
private  static final String PREF_FILE = BuildConfig.APPLICATION_ID.replace(".","_");
private static SharedPreferences sharedPreferences = null;
private static void openPref(Context context) {
sharedPreferences = context.getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE);
}
//For string value
public static String getValue(Context context, String key,String defaultValue) {
Pref.openPref(context);
String result = Pref.sharedPreferences.getString(key, defaultValue);
Pref.sharedPreferences = null;
return result;
}
public static void setValue(Context context, String key, String value) {
Pref.openPref(context);
Editor prefsPrivateEditor = Pref.sharedPreferences.edit();
prefsPrivateEditor.putString(key, value);
prefsPrivateEditor.commit();
Pref.sharedPreferences = null;
}
//You can create method like above for boolean, float, int etc...
}

如果你想存储字符串数据,你可以写如下:

Pref.setValue(mContext,"test", "Test123");

如果你想获取字符串数据,你可以在下面这样写

Pref.getValue(mContext,"test", "your default value");

这一个返回字符串值为"Test123"。如果您在没有setvalue的情况下获取值,那么它将在此处返回您的默认值,它就是"您的缺省值"。

最新更新