[英]How do I Read/Write an ArrayList of Arraylists of Objects to/from a file?
我有一個自定義對象( AppDetails
),它可以成對保存String值( Title
, Details
)。 我已經創建了這個對象的ArrayList
,然后它是另一個ArrayList
的對象。
ArrayList<ArrayList<AppDetails>> appBox;
protected class AppDetails {
protected String DetailTitle;
protected String DetailDesc;
public AppDetails() {
DetailTitle = "";
DetailDesc = "";
}
public void setDetailTitle(String s) {
DetailTitle = s;
}
public void setDetailDesc(String s) {
DetailDesc = s;
}
public String getDetailTitle() {
return DetailTitle;
}
public String getDetailDesc() {
return DetailDesc;
}
}
將其保存到Android內部存儲中的最佳方法是什么? 我希望能夠檢索此appBox
並在應用程序啟動時加載它,並在每次創建新的AppDetails
ArrayList
時將其保存到文件中。
您可以將數據序列化為xml,並使用首選項API保存此類xml。 請參閱首選項API官方頁面 。
簡而言之,以下代碼示例:
sPref = getPreferences(MODE_PRIVATE); //MODE_PRIVATE is a constant means that saved data will be accesed via current app only
Editor ed = sPref.edit(); //Editor for writing data
ed.putString(SAVED_TEXT, stringToWrite); //Prepare the string to save. SAVED_TEXT is a key for xml data chunk that will be saved
ed.commit(); //Save data
對於您的特定示例,可以執行以下操作:
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
for(List<AppDetails> lst : appBox){
for(AppDetails appDetails : lst){
ed.putString(appDetails.DetailTitle, appDetails.DetailText);
}
}
ed.commit();
這可以通過不同的方式來實現。 考慮到數組不應該很大(數十個對象甚至數百個對象),可以將它們作為SharedPreferences插入。 為了使您的生活更輕松,我建議在存儲到SharedPreferences中之前,使用Android中的GSON庫將主數組解析為JSON字符串。 另一種方法是使用SQLite,即數據庫。 您可以如下設計一張表:
Id | MainArrayIndex | Title | Description
1 | 0 | title1 | desc
2 | 1 | title2 | desc
3 | 2 | title3 | desc
4 | 0 | title4 | desc
甚至設計2個表,一個表用於保存指向主數組的索引(這樣可以減小數據大小),另一個表用於存儲數據本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.