Android

커스텀 객체를 sharedpreferences 에 저장하고 불러오기

최데브 2021. 4. 16. 10:23

1. String 형식으로 저장 할때 

public void setStringArrayPref(Context context, String key, ArrayList<String> values) {
        SharedPreferences prefs = context.getSharedPreferences("key", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray a = new JSONArray();
        for (int i = 0; i < values.size(); i++) {
            a.put(values.get(i));
        }
        if (!values.isEmpty()) {
            editor.putString(key, a.toString());
        } else {
            editor.putString(key, null);
        }
        editor.apply();
    }

    public ArrayList<String> getStringArrayPref(Context context, String key) {
        SharedPreferences prefs = context.getSharedPreferences("key", MODE_PRIVATE);
        String json = prefs.getString(key, null);
        ArrayList<String> urls = new ArrayList<String>();
        if (json != null) {
            try {
                JSONArray a = new JSONArray(json);
                for (int i = 0; i < a.length(); i++) {
                    String url = a.optString(i);
                    urls.add(url);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }

2. 커스텀 객체를 저장 할때

    public void setStringArrayPref(Context context, String key, ArrayList<Data> values) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray a = new JSONArray();
        Gson gson =new GsonBuilder().create();
        for (int i = 0; i < values.size(); i++) {
            String string = gson.toJson(values.get(i), Data.class);
            a.put(string);
        }
        if (!values.isEmpty()) {
            editor.putString(key, a.toString());
        } else {
            editor.putString(key, null);
        }
        editor.apply();
    }

    public ArrayList<OrderData> getStringArrayPref_item(Context context, String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String json = prefs.getString(key, null);
        ArrayList<OrderData> OrderDatas = new ArrayList<OrderData>();
        Gson gson =new GsonBuilder().create();
        if (json != null) {
            try {
                JSONArray a = new JSONArray(json);
                for (int i = 0; i < a.length(); i++) {
                    OrderData orderData = gson.fromJson( a.get(i).toString() , OrderData.class);
                    OrderDatas.add(orderData);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return OrderDatas;
    }

 

반응형