Car*_*nal 43 serialization android sharedpreferences
我知道SharedPreferences有putString(),putFloat(),putLong(),putInt()和putBoolean().但我需要存储一个对象,它是类型的Serializable在SharedPreferences.我怎样才能做到这一点?
Chr*_*s.D 46
总之,你不能尝试将对象序列化为私有文件,这相当于同样的事情.样本类如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.content.Context;
/**
*
* Writes/reads an object to/from a private local file
*
*
*/
public class LocalPersistence {
/**
*
* @param context
* @param object
* @param filename
*/
public static void witeObjectToFile(Context context, Object object, String filename) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
// do nowt
}
}
}
}
/**
*
* @param context
* @param filename
* @return
*/
public static Object readObjectFromFile(Context context, String filename) {
ObjectInputStream objectIn = null;
Object object = null;
try {
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e) {
// Do nothing
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
// do nowt
}
}
}
return object;
}
}
Run Code Online (Sandbox Code Playgroud)
ישו*_*ותך 30
接受的答案具有误导性,我们可以使用GSON将可序列化对象存储到SharedPreferences中.在google-gson上阅读更多相关信息.
您可以在Gradle文件中添加GSON依赖项:
compile 'com.google.code.gson:gson:2.7'
Run Code Online (Sandbox Code Playgroud)
这里的片段:
首先,创建您通常的sharedPreferences:
//Creating a shared preference
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)
从可序列化对象保存到首选项:
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(YourSerializableObject);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
Run Code Online (Sandbox Code Playgroud)
从首选项获取可序列化对象:
Gson gson = new Gson();
String json = mPrefs.getString("SerializableObject", "");
yourSerializableObject = gson.fromJson(json, YourSerializableObject.class);
Run Code Online (Sandbox Code Playgroud)
Eli*_*old 15
没有文件就可以做到这一点.
我正在将信息序列化到base64,像这样我可以将它保存为首选项中的字符串.
以下代码是将序列化对象序列化为base64字符串,反之亦然:import android.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectSerializerHelper {
static public String objectToString(Serializable object) {
String encoded = null;
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
encoded = new String(Base64.encodeToString(byteArrayOutputStream.toByteArray(),0));
} catch (IOException e) {
e.printStackTrace();
}
return encoded;
}
@SuppressWarnings("unchecked")
static public Serializable stringToObject(String string){
byte[] bytes = Base64.decode(string,0);
Serializable object = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream( new ByteArrayInputStream(bytes) );
object = (Serializable)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (ClassCastException e) {
e.printStackTrace();
}
return object;
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以使用 Kotlin 创建易于使用的语法。
@Throws(JsonIOException::class)
fun Serializable.toJson(): String {
return Gson().toJson(this)
}
@Throws(JsonSyntaxException::class)
fun <T> String.to(type: Class<T>): T where T : Serializable {
return Gson().fromJson(this, type)
}
@Throws(JsonIOException::class)
fun SharedPreferences.Editor.putSerializable(key: String, o: Serializable?) = apply {
putString(key, o?.toJson())
}
@Throws(JsonSyntaxException::class)
fun <T> SharedPreferences.getSerializable(key: String, type: Class<T>): T? where T : Serializable {
return getString(key, null)?.to(type)
}
Run Code Online (Sandbox Code Playgroud)
然后SharedPreferences使用类似的方法保存任何可序列化的get/put()
此处完整要点将可序列化文件保存在与 Kotlin 和 GSON 共享的首选项中
正如其他答案中提到的,当数据类结构发生变化时,您可能必须考虑迁移。或者至少必须更改您用来存储的密钥。