Last active
September 12, 2020 10:31
-
-
Save hossinasaadi/ba2bc26811ae58a31046769e70d14c8d to your computer and use it in GitHub Desktop.
save List as SharedPreferences Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.List; | |
| public class DataList { | |
| List<Data> dataList; | |
| public List<Data> getDataList() { | |
| return dataList; | |
| } | |
| public void setDataList(List<Data> dataList) { | |
| this.dataList = dataList; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| compile 'com.google.code.gson:gson:2.7' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| List<Data> fetchLog = new ArrayList<Data>(); | |
| DataList dataList = null; | |
| dataList = new DataList(); | |
| Gson gson = new Gson(); | |
| // SAVE List As SharedPreferences | |
| Data data = new Data("ali",20); | |
| fetchLog.add(data); | |
| dataList.setDataList(fetchLog); | |
| Gson gson = new Gson(); | |
| String json = gson.toJson(dataList); | |
| utils.setPref("logs", json);// function to set SharedPreferences | |
| // read List from SharedPreferences | |
| String json = utils.getPref("logs");// function to read SharedPreferences | |
| if (! json.equals("")) { | |
| dataList = gson.fromJson(json, DataList.class); | |
| fetchLog = dataList.getDataList(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment