当我的应用程序启动时,它会连接到数据库并以XML格式下载一些数据。这是布局:
<Customers>
<Customer>
<name>...</name>
...
</Customer>
<Customer>
<name>...</name>
...
</Customer>
...
</Customer>
对于每个客户,我创建了一个类Customer
的Object,它存储在ArrayList中。用户可以编辑和添加每个客户的一些数据,他们可以将其上传回服务器。
问题在于我不知道在本地存储数据的最佳方式是什么,因此如果我的应用程序关闭或用户不再拥有互联网,他们将有备份。我现在将所有Customer
对象转换回XML,然后将其存储在SD卡上,但我认为这不是一个好的解决方案。每个客户都有大约40个字符串,10个整数和一些我必须存储的布尔值。有没有更好的方法在本地存储数据?
我发现some code可以存储一个ArrayList,但它不能用于自定义类。
修改:我使用this tutorial来解决问题。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import android.os.Environment;
public class SerializeData {
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch (IOException ioe) {
CreateLog.addToLog(ioe.toString());
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch (ClassNotFoundException cnfe) {
CreateLog.addToLog(cnfe.toString());
return null;
} catch (IOException ioe) {
CreateLog.addToLog(ioe.toString());
return null;
}
}
public static void saveData(){
byte[] arrayData = SerializeData
.serializeObject(MyTasks.allCustomers);
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/myprogram/myarray.txt"));
bos.write(arrayData);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
CreateLog.addToLog(e.toString());
} catch (IOException e) {
CreateLog.addToLog(e.toString());
}
}
public static ArrayList<Customer> getData(){
File afile = new File(Environment.getExternalStorageDirectory()
+ "/myprogram/myarray.txt");
int size = (int) afile.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(afile));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
CreateLog.addToLog(e.toString());
} catch (IOException e) {
CreateLog.addToLog(e.toString());
}
return (ArrayList<Customer>) SerializeData.deserializeObject(bytes);
}
}