You are on page 1of 7

Stack Overflow

Questions

Tags

Users

sign up
Badges

Unanswered

log in

Ask

Read this post in our app!

Saving and Reloading ListView using Shared Preferences [Saving onDestroy()]


3

android

listview

android-listview

save

I am creating a To Do List. Right now my app adds and removes data to and from a ListView. However, when I close my application the data
gets erased. I want to use SharedPreferences to save the data onDestroy(), then when my app opens I wanted the data to reload.
However, I don't know how to go about accomplishing this task. Can anybody help me with saving a ListView using Shared Preferences (aka I
am looking for code)?
There are tutorials for just one shared preference I am looking to dynamically add multiple strings when my application closes. Then when I
reopen it, the data will appear. I am only using ONE ACTIVITY page, everything will occur on one page.
HERE IS MY CODE:

public class Main_ToDoList extends Activity implements OnClickListener


{
private Button btnAdd;
private EditText et;
private ListView lv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnAdd = (Button)findViewById(R.id.addTaskBtn);
btnAdd.setOnClickListener(this);
et = (EditText)findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml

share

improve this question


JustAnotherUser32
42 3 12

Asked
Sep 9 '13 at 17:02

Why dont use a database? Stefano Munarini Sep 9 '13 at 17:07

add a comment

3 Answers

order by votes

Android SharedPreferences is used to store a single key-value paired data. In other words, it is not made to store repetitive and
complex data. In your case, a list view may contain than 100 rows or more depends on your app. If you were to create a
SharedPreferences object for each row it would be 100+ of it, which is not efficient at all. The solution for this is as suggested above,
is to use the Android's SQLite database.

A good tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

share

improve this answer


Gricher
100 6

Answered
Mar 4 '14 at 16:36

As suggested by Stefano Munarini, you can use a database.


On the other hand, you can loop on the elements of your ArrayAdapter (wrapping your ArrayList) and store them to your
SharedPreferences as in:
public static final String PREFERENCES_TODO = "TODO_List_Shared_Preferences";
// ...
SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_TODO,
MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// This will remove all entries of the specific SharedPreferences
editor.clear();
for (int i = 0; i < adapter.getCount(); ++i){
// This assumes you only have the list items in the SharedPreferences.
editor.putString(String.valueOf(i), adapter.getItem(i));
}
editor.commit();
// ...
// And the reverse process:
SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_TODO,
MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = prefs.getString(Integer.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {

Some considerations:
Save SharedPreferences in onPause() rather than in onDestroy() which is not guaranteed to be called. See Activity Lifecycle for
reference.
Forbid user from inputing an empty String. (Edit: You are already doing that.)

If you know there won't be 2 identical String (forbidden or otherwise), you can use the SharedPreferences.Editor.putStringSet(String,
Set<String>) to use a single entry.
If there is a lot of elements or if you're planning on adding extra options (i.e. Due date, Category, etc.) You should really consider
the database options since the SharedPreferences solution doesn't provide good scalability.

share

improve this answer


Sustain
141 4

Answered
Sep 9 '13 at 18:34

Edited
Sep 10 '13 at 9:48

Is this answering your question? Sustain Oct 18 '13 at 0:47

add a comment

I know its old but i want to share my solution for those who Still want to use sharepref and see this post.
1) create custom class that extends ArrayAdapter and override the toString method.just append and put ',' between every line.

public class GroceryArrayAdapter extends ArrayAdapter<String> {


public GroceryArrayAdapter(Context context, int resource) {
super(context, resource);
}
public GroceryArrayAdapter(Context context, int resource, int
super(context, resource, textViewResourceId);
}
public GroceryArrayAdapter(Context context, int resource, int
super(context, resource, textViewResourceId, objects);
}

textViewResourceId) {

textViewResourceId, String[] objects) {

public GroceryArrayAdapter(Context context, int resource, String[]


super(context, resource, objects);
}

objects) {

public GroceryArrayAdapter(Context context, int resource, List<String> objects) {


super(context, resource, objects);
}

2)Save the data as one string. put it in onPause()


private void saveData(){
sharedPrefs = activity.getSharedPreferences(Constants.APPSharePref,
Context.MODE_PRIVATE);
SharedPreferences.Editor e = sharedPrefs.edit();
e.putString(Constants.GROCERY,**grocery_adapter.toString()**);
e.commit();
}

3)In onResume restore the data back by splinting the string with ',' and add it to the adapter.

private void loadDataFromPref(){


sharedPrefs = getActivity().getSharedPreferences(Constants.APPSharePref,
Context.MODE_PRIVATE);

share

String gList =sharedPrefs.getString(Constants.GROCERY,"");


if(!"".equals(gList) && ""!=gList){
String [] str = gList.split(",");
for (String item : str) {
grocery_adapter.add(item);
}
}

improve this answer


Maor Hadad
667 4 14

Your Answer

log in

Answered
May 22 '15 at 0:32

or
Name

Email

By posting your answer, you agree to the privacy policy and terms of service.

meta chat tour help blog privacy policy legal contact us full site
Download the Stack Exchange Android app
2016 Stack Exchange, Inc

Post Your Answer

You might also like