0

I have an activity which contains a ListView populated with strings. But when I close the app and reopen it, it is empty again. How do I save the content so that the next time I open the app, the ListView is still populated?

Thanks

Donev
  • 23
  • 3

1 Answers1

1

To store data permanently you can use one of these options :

  • SharedPreferences : Store private primitive data in key-value pairs. ( and this what I suggest )

To store data in SharedPreferences :

SharedPreferences data = getSharedPreferences("my_data_pref", 0);
SharedPreferences.Editor editor = data.edit();
editor.putString("key", "value");
editor.commit();
  • SQLite Databases : Store structured data in a private database.

  • Internal Storage or External Storage

Fouad Wahabi
  • 804
  • 7
  • 16
  • I have this ArrayList: ArrayList lista = new ArrayList(); how do I save it with SharedPreferences? – Donev May 09 '15 at 17:58
  • You have just to iterate over the `ArrayList` than store the values with keys depending on the index of the value, for example like this : editor.putString("list-" + i, "value"); // i is the index of the `String` in th `ArrayList` – Fouad Wahabi May 09 '15 at 18:07
  • Could you please be more specific, since I`m a beginner and this is the first time that I work in android. So, I have an ArrayList of strings in which the user will add strings every time he opens the app. How do I save it with SharedPreferences? What is the exact code that I need to write and in which function do I write it? – Donev May 11 '15 at 15:59
  • @Donev sorry but what do you mean by " every time he opens the app " , can you give me summary about your app so to give you a more conscious answer – Fouad Wahabi May 11 '15 at 16:05
  • It`s an app for quotes. I generate quotes as strings in TextView and if the user likes the quote, he/she puts it in favorites (which is another activity). The quote is added in a String ArrayList and then the whole ArrayList of favorite quotes is sent to the other activity where it shows all the favorites in a ListView. So I need the strings (quotes) to be saved in the ArrayList for when the user closes the app and then opens it again. – Donev May 11 '15 at 16:13
  • In this case you have to use `SQLite` database ( you can read this to understand why : http://stackoverflow.com/questions/6276358/pros-and-cons-of-sqlite-and-shared-preferences ) , so you can find a good tutotial about using `SQLite` here : http://www.vogella.com/tutorials/AndroidSQLite/article.html – Fouad Wahabi May 11 '15 at 16:48