Saving Serializable Objects List into sharedPreferences

前端 未结 5 1073
闹比i
闹比i 2020-12-03 05:10

Can anyone tell me how I can save a list of custom Serializable objects into SharedPreference? I am new To Android and I want to save an Arr

5条回答
  •  时光说笑
    2020-12-03 05:45

    try this, works for me :

    implementation 'com.google.code.gson:gson:2.7'
    

    DataList.java :

    import java.util.List;
    
    public class DataList {
        List dataList;
    
        public List getDataList() {
            return dataList;
        }
    
        public void setDataList(List dataList) {
            this.dataList = dataList;
        }
    }
    

    MainActivity.java :

        List fetchLog = new ArrayList();
        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();
            }
    

提交回复
热议问题