Reputation: 1
I have a custom object (AppDetails
) that saves String values in pairs (Title
, Details
).
I have made an ArrayList
of this object, which is then the object of another 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;
}
}
What is the best way to save this into internal storage in Android?
I want to be able to retrieve this appBox
and load it on app startup, and save it to file every time a new ArrayList
of AppDetails
is created.
Upvotes: 0
Views: 174
Reputation:
You can serialize your data to xml and save such xml using preference API. See preference API official page.
In a nutshell, the following code sample:
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
For your specific example it's possible to do something like the following:
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();
Upvotes: 1
Reputation: 2840
This can be achieved in different ways. Considering that the arrays are not supposed to be large (tens of objects or even hundreds) you can insert them as SharedPreferences. To make your life easier i would suggest to parse the main array into a JSON string using GSON library in Android before storing into SharedPreferences. Another approach would be to use SQLite, so a database. You may design 1 table as follows:
Id | MainArrayIndex | Title | Description
1 | 0 | title1 | desc
2 | 1 | title2 | desc
3 | 2 | title3 | desc
4 | 0 | title4 | desc
Or even design 2 tables, one for holding the index to the main array (so you would reduce the data size) and one for storing the data themselves.
Upvotes: 0