[英]Write an ArrayList to SD-Card
當我的應用程序啟動時,它會連接到數據庫並以XML格式下載一些數據。 這是布局:
<Customers>
<Customer>
<name>...</name>
...
</Customer>
<Customer>
<name>...</name>
...
</Customer>
...
</Customer>
對於每個客戶,我創建一個存儲在ArrayList中的類Customer
的對象。 用戶可以編輯和添加每個客戶的一些數據,然后可以將其上傳回服務器。
問題是我不知道什么是在本地存儲數據的最佳方法,因此,如果我的應用程序關閉或用戶不再有互聯網,他們將有一個備份。 現在,我將所有Customer
對象轉換回XML,然后將其存儲在SD卡上,但是我認為這不是一個好的解決方案。 每個客戶有大約40個String,10個整數和一些我必須存儲的布爾值。 有沒有更好的方法在本地存儲數據?
我發現一些代碼可以存儲ArrayList,但不適用於自定義類。
編輯:我使用本教程來解決我的問題。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.