3

I am creating a media player app where users can play a list of songs from either their local library or remotely. I have stored the songs they would obtain from either location in an Arraylist of songs object. What I want is to allow users the ability to save a list of songs as their playlist in Share Preference and be able to add more playlist to existing playlist. How to I achieve this, thank you.

store list [
  playlist: {
     id: 1,
     name: My Playlist,
     songs: 
     [
         { name: 'Song 1', album: 'Album', ...}  
         { name: 'Song 2', album: 'Album', ...}
         { name: 'Song 3', album: 'Album', ...}  
     ]
 },

  playlist: {
      id: 2,
      name: My Playlist Two,
      songs: 
      [
           { name: 'Song 1', album: 'Album', ...}  
           { name: 'Song 2', album: 'Album', ...}
           { name: 'Song 3', album: 'Album', ...}  
      ]
  }
 ]
Dimitar
  • 4,402
  • 4
  • 31
  • 47
Flavah
  • 103
  • 7
  • So first of all, is your data in JSON format? Because yours will not pass parser. If it's JSON, please refer to this [post](http://stackoverflow.com/questions/5918328/is-it-ok-to-save-a-json-array-in-sharedpreferences). – solosodium Jun 30 '16 at 20:23

2 Answers2

1

If you're really set on using shared preferences you could parse the array to a JSONarray and store it that way. This answer from another question may help.

I would suggest using internal storage and implementing something like this to store your array:

String filename = "myfile";
String[] numbers = new String[] {"1, 2, 3"};
FileOutputStream outputStream;

try { 
  outputStream = openFileOutput(filename, Context.MODE_APPEND);
  for (String s : numbers) {  
      outputStream.write(s.getBytes());  
  }  
  outputStream.close();

} catch (Exception e) {
    e.printStackTrace();
} 

Here's a link to all the storage options Android offers: https://developer.android.com/guide/topics/data/data-storage.html

Community
  • 1
  • 1
Aidan Laing
  • 1,260
  • 11
  • 23
0

Shared preference is not the best object for you. It is not the objectif. It is more for configuration. For example, you want to change the language of an app, you store the new language on a preference. Storing complexe object is not a good idea

Try with a database sqlite. Store in the database and table all the needed information and load it with a cursor.

https://www.google.fr/url?sa=t&source=web&rct=j&url=https://developer.android.com/training/basics/data-storage/databases.html&ved=0ahUKEwi5n96oz9DNAhXBsxQKHYeqC5kQFggjMAI&usg=AFQjCNGZO3o7XvDtwLTPzOclCuVkMgDc0A&sig2=19A1656hR_irXRh1hwn1Zg

And with that you can also use the content providers and get all the local music file.

kevingiroux
  • 155
  • 1
  • 14
  • Noted... I totally agree but I was trying to avoid writing sqlite CRUD queries. I will implement my task using the sqlite method. Thanks you all for your inputs. – Flavah Jul 01 '16 at 14:50