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

前端 未结 2 655
迷失自我
迷失自我 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: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>() {}.getType();
    ArrayList arrayList = gson.fromJson(json, type);
    

    Original answer: Storing Array List Object in SharedPreferences

提交回复
热议问题