-1

I'm working on an app that allow user to scheduled download (user can select multiple links and then at the specific given time (it may take even weeks), AlarmManager will send broadcast to call the DownloadService

So how do I save the selected links of user, even when the app is closed? I think those links just need to be a ArrayList.

I tried SharedPreferences but it only allow me to putInt, putBoolean... I also read about onSaveInstanceState / onRestoreInstanceState but when the app is closed, saveInstanceState is also gone, right?

How can I do this? Thank you very much

0xh8h
  • 3,271
  • 4
  • 34
  • 55
  • SharedPreferences can store Strings too http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putString – panini Jul 01 '14 at 04:17
  • putExtra(), allows you to store string, did you know about that? – Bassel Serio Jul 01 '14 at 04:19
  • Try this link http://stackoverflow.com/questions/7361627/how-can-write-code-to-make-sharedpreferences-for-array-in-android/7361989#7361989 – Hariharan Jul 01 '14 at 04:22
  • I know SharedPreference let me store String, that why I put the "..." after. But if with each url that user selected, I store it with a key in SharedPreference file, this file will be a mess, and I don't want that. Sorry if I didn't clear my intention in my post above. I want to know a way (a good way) to store a lot of url (even 1000) into the app so that when the app closed, the url is still exist. – 0xh8h Jul 01 '14 at 04:59

1 Answers1

1

If you have an ArrayList<String> urlsList;

Saving URLs :

Editor edit = prefs.edit();
edit.putInt("list_size", urlsList.size());
for(int i=0;i<urlsList.size(); i++)
    edit.putString("url_" + i, urlsList.get(i));
edit.commit();

Retrieving URLs :

int size = prefs.getInt("list_size", 0);
ArrayList<String> retrievedUrls = new ArrayList<String();
for(int i=0; i<size; i++)
    retrievedUrls.add(prefs.getString("url_" + i, null)); 
Shivam Verma
  • 7,973
  • 3
  • 26
  • 34
  • The problem with this approach is that you'll pollute your preferences. Say, you save an array with 100 entries and then shrink it ito 2. You'll still have 100 entries in your preferences unless you clean it up first. – Aniruddha Jul 01 '14 at 04:34
  • Yep sure is. But it can be done. In an ideal situation he should be using the sqlite database. – Shivam Verma Jul 01 '14 at 04:36
  • Can you please clarify the sqlite database solution? Your solution above is get things done but it absolutely make my SharedPreference file a mess. Thank you very much – 0xh8h Jul 01 '14 at 04:56
  • Just use the SQLite db to save and retrieve URLs. This is an exhaustive tutorial : http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ – Shivam Verma Jul 01 '14 at 04:59