c# - "Operation is not valid due to the current state of the object." Error when trying to create new List< AudioTrack> from JsonFile in WP8 -
i'm trying make music app , have 2 project in solution: main project , audioplaybackagent (apa) project. when chose song main project (which contained in list of song) , copied whole list json file in isolate storage , read apa project.
problem is, error when tried create new audiotrack items in json file
code create file (from main project)
public static void createonlinelist(string id, observablecollection<basicitemmodel> list) { using (isolatedstoragefile file = isolatedstoragefile.getuserstoreforapplication()) { string filename = "onlinelist.json"; jobject obj = new jobject(); jarray arr = new jarray(); (int dem = 0; dem < list.count(); dem++) { if (list[dem].id == id) obj.add("index", dem); jobject item = new jobject(); item.add("name", list[dem].name); item.add("artist", list[dem].artist); item.add("url", list[dem].url); arr.add(item); } obj.add("list", arr); string jsonstring = jsonconvert.serializeobject(obj); using (isolatedstoragefilestream stream = file.openfile(filename,filemode.openorcreate,fileaccess.write)) { using (streamwriter writer = new streamwriter(stream)) { writer.writeline(jsonstring); } } } }
code read file (from apa project)
public static void readonlinelist() { using (isolatedstoragefile file = isolatedstoragefile.getuserstoreforapplication()) { string filename = "onlinelist.json"; string jsonstring = ""; using (isolatedstoragefilestream stream = file.openfile(filename, filemode.open, fileaccess.read)) { using (streamreader writer = new streamreader(stream)) { jsonstring = writer.readline(); } } jobject obj = new jobject(); obj = jobject.parse(jsonstring); audioplayer.currenttracknumber = int.parse(obj["index"].tostring()); list<jtoken> arr = obj["list"].tolist(); if (audioplayer.playlist == null) audioplayer.playlist = new list<audiotrack>(); else audioplayer.playlist.clear(); foreach (var item in arr) { audiotrack track = new audiotrack() { source = new uri(item["url"].tostring(), urikind.absolute), title = item["name"].tostring(), artist = item["artist"].tostring(), album = null }; //// error of line when trying create track audioplayer.playlist.add(track); } } }
the audiotrack object has strange behaviour , there 2 ways in can insert/edit data audiotrack.
in case accessing properties , generate error getting.
you can 1 of 2 things:
option 1 - insert data in constructor
audiotrack track = new audiotrack(new uri(item["url"].tostring(), urikind.absolute), item["artist"].tostring(), null, null);
option 2 - use beginedit() , endedit() methods
audiotrack track = new audiotrack(); track.beginedit(); track.source = new uri(item["url"].tostring(), urikind.absolute); track.title = item["name"].tostring(); track.artist = item["artist"].tostring(); track.endedit();
i hope helps , answers question.
Comments
Post a Comment