Store ArrayList in Android after app closes
I have an ArrayList of Strings from which I am drawing a ListView. In the app, the user can add items to the ArrayList, causing an item to be displayed on the ListView. While the ap开发者_StackOverflow中文版p is running, the ArrayList retains its items, but after a reboot (or any other time when the app stops) the items are lost. I've read about internal, external, and SQLite storage, but I couldn't get internal nor external storage to work, and I know nothing about SQLite and the app is due Friday. Is there a better implementation of saving? I've attached a complete copy of the code without any storage methods for review.
Thanks.
http://www.mediafire.com/?tf8093g39jv0f61 <-- code
Use the preferences implementation to save the ArrayList<String>
. In the onPause
method use this:
ArrayList<String> tobesaved = getData(); // fetch the data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("SAVEDATA", new HashSet<String>(tobesaved));
edit.commit();
and then you can fetch it in the onResume
method:
ArrayList<String> retrieved = new ArrayList<String>(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getStringSet("SAVEDATA", new HashSet<String>()));
EDIT: I didn't get a chance to look at your code: mediafire tried to open some popup on my browser so I quickly closed the tab, but that should work for you. Try and perhaps use gist (at http://gist.github.com) or pastebin (at http://pastebin.com/) instead to share longer code sequences.
you can go for the Serializable idea refer the following links you may get a idea
http://developer.android.com/reference/java/io/Serializable.html
and
http://www.jondev.net/articles/Android_Serialization_Example_%28Java%29
ArrayList<String> tobesaved = getData(); // fetch the data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("SAVEDATA", new HashSet<String>(tobesaved));
edit.commit();
ArrayList<String> retrieved = new ArrayList<String>(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getStringSet("SAVEDATA", new HashSet<String>()));
This Code works, but I have my Arraylist sorted alphabetically. This hashSet messes up the alphabetical organizations of my strings. . . Anyone can make this answer, great to PERFECT? By making ArrayList save and load with the same order??
精彩评论