공유 환경 설정에서 클래스 객체 저장 및 검색
Android에서 클래스의 객체를 공유 환경 설정으로 저장하고 나중에 객체를 검색 할 수 있습니까?
가능하다면 어떻게해야합니까? 가능하지 않다면 다른 가능성은 무엇입니까?
직렬화가 하나의 옵션이라는 것을 알고 있지만 공유 환경 설정을 사용하여 가능성을 찾고 있습니다.
불가능합니다.
SharedPrefences SharePreferences 에는 간단한 값만 저장할 수 있습니다.
수업에서 특별히 무엇을 저장해야합니까?
예, 우리는 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>가 있습니다. 처음에는 MyClass에 JSON 객체로 변환하는 메소드를 추가했습니다.
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;
}
공유 환경 설정의 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();
Gradle Build.gradle을 사용하여 GSON을 사용할 수 있습니다.
implementation 'com.google.code.gson:gson:2.8.0'
Then in your code, for example pairs of string/boolean with Kotlin :
val nestedData = HashMap<String,Boolean>()
for (i in 0..29) {
nestedData.put(i.toString(), true)
}
val gson = Gson()
val jsonFromMap = gson.toJson(nestedData)
Adding to SharedPrefs :
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
sharedPrefEditor.putString("sig_types", jsonFromMap)
sharedPrefEditor.apply()
Now to retrieve data :
val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
Log.i("myvalues", key.toString() + map.get(key).toString())
}
You can do it using PowerPreference
library in 3 easy steps!
https://github.com/AliAsadi/PowerPreference
1. Create Object
Object obj = new Object();
2. Write to shared preference
PowerPreference.getDefaultFile().put("object",obj);
3. Getting the object
Object obj = PowerPreference.getDefaultFile()
.getObject("object", Object.class);
Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc
You can use Complex Preferences Android - by Felipe Silvestre library to store your custom objects. Basically, it's using GSON mechanism to store objects.
To save object into prefs:
User user = new User();
user.setName("Felipe");
user.setAge(22);
user.setActive(true);
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);
complexPreferences.commit();
And to retrieve it back:
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);
Do you need to retrieve the object even after the application shutting donw or just during it's running ?
You can store it into a database.
Or Simply create a custom Application class.
public class MyApplication extends Application {
private static Object mMyObject;
// static getter & setter
...
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application ... android:name=".MyApplication">
<activity ... />
...
</application>
...
</manifest>
And then from every activities do :
((MyApplication) getApplication).getMyObject();
Not really the best way but it works.
There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,
Yes .You can store and retrive the object using Sharedpreference
참고URL : https://stackoverflow.com/questions/5418160/store-and-retrieve-a-class-object-in-shared-preference
'program tip' 카테고리의 다른 글
JavaScript에 중복이 포함 된 배열에서 고유 한 값의 배열을 얻는 방법은 무엇입니까? (0) | 2020.08.06 |
---|---|
Android startActivity () 전환 애니메이션을 변경할 수 있습니까? (0) | 2020.08.06 |
RecyclerView에서 match_parent 너비가 작동하지 않습니다 (0) | 2020.08.06 |
UIImage를 가로로 뒤집는 방법? (0) | 2020.08.06 |
스위프트를 사용하여 iPhone을 진동시키는 방법? (0) | 2020.08.06 |