공유 환경 설정에서 클래스 객체 저장 및 검색 검색 할 수

Android에서 클래스의 객체를 공유 환경 설정에 저장하고 나중에 객체를 검색 할 수 있습니까?

가능하다면 어떻게해야합니까? 가능하지 않다면 다른 가능성은 무엇입니까?

직렬화가 하나의 옵션이라는 것을 알고 있지만 공유 기본 설정을 사용하여 가능성을 찾고 있습니다.



답변

불가능합니다.

SharedPrefences SharePreferences.Editor 에는 단순 값만 저장할 수 있습니다.

특히 저장해야 할 수업은 무엇입니까?


답변

예, 다음을 사용하여 수행 할 수 있습니다. Gson을

GitHub 에서 작업 코드 다운로드

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

저장을 위해

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

얻기 위해

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

업데이트 1

최신 버전의 GSON은 github.com/google/gson 에서 다운로드 할 수 있습니다. .

업데이트 2

Gradle / Android Studio를 사용하는 경우 build.gradle종속성 섹션 에 다음을 입력 하십시오.

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

답변

Outputstream을 사용하여 Object를 내부 메모리로 출력 할 수 있습니다. 그리고 문자열로 변환 한 다음 기본 설정에 저장합니다. 예를 들면 :

    mPrefs = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor ed = mPrefs.edit();
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    ObjectOutputStream objectOutput;
    try {
        objectOutput = new ObjectOutputStream(arrayOutputStream);
        objectOutput.writeObject(object);
        byte[] data = arrayOutputStream.toByteArray();
        objectOutput.close();
        arrayOutputStream.close();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
        b64.write(data);
        b64.close();
        out.close();

        ed.putString(key, new String(out.toByteArray()));

        ed.commit();
    } catch (IOException e) {
        e.printStackTrace();
    }

Preference에서 Object를 추출해야 할 때. 아래와 같이 코드를 사용하십시오.

    byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
    if (bytes.length == 0) {
        return null;
    }
    ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
    Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
    ObjectInputStream in;
    in = new ObjectInputStream(base64InputStream);
    MyObject myObject = (MyObject) in.readObject();

답변

나는 같은 문제가 있었고 여기 내 해결책이 있습니다.

공유 기본 설정에 저장하려는 MyClass 및 ArrayList <MyClass> 클래스가 있습니다. 처음에는 JSON 객체로 변환하는 메서드를 MyClass에 추가했습니다.

public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("id", this.id);
        obj.put("name", this.name);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

다음은 “ArrayList <MyClass> items”개체를 저장하는 방법입니다.

SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
    SharedPreferences.Editor editor = mPrefs.edit();

    Set<String> set= new HashSet<String>();
    for (int i = 0; i < items.size(); i++) {
        set.add(items.get(i).getJSONObject().toString());
    }

    editor.putStringSet("some_name", set);
    editor.commit();

객체를 검색하는 방법은 다음과 같습니다.

public static ArrayList<MyClass> loadFromStorage() {
    SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);

    ArrayList<MyClass> items = new ArrayList<MyClass>();

    Set<String> set = mPrefs.getStringSet("some_name", null);
    if (set != null) {
        for (String s : set) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                Long id = jsonObject.getLong("id"));
                String name = jsonObject.getString("name");
                MyClass myclass = new MyClass(id, name);

                items.add(myclass);

            } catch (JSONException e) {
                e.printStackTrace();
         }
    }
    return items;
}

Shared Preferences의 StringSet은 API 11부터 사용할 수 있습니다.


답변

Gson 라이브러리 사용 :

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}

저장:

Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);

검색:

String json = getPrefs().getUserJson();

답변

PowerPreference라이브러리를 사용하여 3 단계로 쉽게 할 수 있습니다 !

https://github.com/AliAsadi/PowerPreference

1. 개체 만들기

Object obj = new Object();

2. 공유 기본 설정에 쓰기

PowerPreference.getDefaultFile().put("object",obj);

3. 개체 얻기

Object obj = PowerPreference.getDefaultFile()
                            .getObject("object", Object.class);

답변

이 객체-> TinyDB–Android-Shared-Preferences-Turbo를 사용 하면 매우 간단합니다. 배열, 정수, 문자열 목록 등과 같이 일반적으로 사용되는 대부분의 객체를 저장할 수 있습니다.