本文介绍了Android的 - 共享preferences与序列化的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道,共享preferences有putString(),putFloat(),putLong(),putInt()和butBoolean()。但我需要存储一个对象,它的类型是序列化的共享preferences的。我怎样才能做到这一点?
I know that SharedPreferences has putString(), putFloat(), putLong(), putInt() and butBoolean(). But I need to store an object that is of type Serializable in SharedPreferences. How can I achieve this?
最好的问候。
推荐答案
总之你不能,试试你的序列化对象的私有文件,它相当于同样的事情。下面的示例类:
In short you cant, try serializing your object to a private file, it amounts to the same thing. sample class below:
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;
}
}
这篇关于Android的 - 共享preferences与序列化的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!