android - 是否可以将数组或对象添加到 Android 上的 SharedPreferences

标签 android android-preferences sharedpreferences

我有一个 ArrayList 对象,这些对象有一个名称和一个图标指针,我想将它保存在 SharedPreferences 中。我该怎么办?

注意:我不想使用数据库

最佳答案

无论 API 级别如何,请检查 String arrays and Object arrays in SharedPreferences


保存数组

public boolean saveArray(String[] array, String arrayName, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i=0;i<array.length;i++)  
        editor.putString(arrayName + "_" + i, array[i]);  
    return editor.commit();  
} 

加载阵列

public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}  

关于android - 是否可以将数组或对象添加到 Android 上的 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3876680/

相关文章:

android - 在 Android 中使 ListPreference 多项选择的简单方法?

android - 使用 LinearLayout 模拟首选项外观/感觉

android - 如何在 Android 中的 native View 之上覆盖 PhoneGap 的 CordovaWebView?

android - 您的 Realm 是从没有 Looper 的线程中打开的

android - 使用 google play 服务自动将 android apk 推送到 google play

android - 如何让我的 SharedPreferences 对象在应用程序关闭后保存数据?

android - getDefaultSharedPreferences 和 MODE_MULTI_PROCESS

android - Android 中的动画

android - android.support.v7.preference.Preference 找不到 onCreateView() 方法

android - 使用 adb 命令删除共享首选项