Android: How to store array of strings in SharedPreferences for android

前端 未结 2 645
迷失自我
迷失自我 2020-12-30 17:33

I\'m building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just l

相关标签:
2条回答
  • 2020-12-30 18:17

    SAVE ARRAY

    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();  
    } 
    

    LOAD ARRAY

    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;  
    }
    
    0 讨论(0)
  • 2020-12-30 18:19

    Convert your array or object to Json with Gson library and store your data as String in json format.

    Save;

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    Editor editor = sharedPrefs.edit();
    Gson gson = new Gson();
    
    String json = gson.toJson(arrayList);
    
    editor.putString(TAG, json);
    editor.commit();
    

    Read;

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    Gson gson = new Gson();
    String json = sharedPrefs.getString(TAG, null);
    Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
    ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
    

    Original answer: Storing Array List Object in SharedPreferences

    0 讨论(0)
提交回复
热议问题