Monday, 15 August 2011

Android - trying to save ArrayList into SharedPreferences as a JSON String using GSON - But filthy NullPointerException appears -



Android - trying to save ArrayList <String> into SharedPreferences as a JSON String using GSON - But filthy NullPointerException appears -

been @ while, can't seem see problem is.

i getting nullpointerexception when attempting save arraylist json, means skip ahead bottom marked.

i have used gson save object , json before, whole objects not arraylists..

relevant code:

private static final string shared_preferences = "shared_preferences"; // shared preferences containing json object of saved usernames sharedpreferences sharedpreferences; // saved usernames arraylist <string> savedusernames;

oncreate()...

// sharedpreferences sharedpreferences = this.getsharedpreferences(shared_preferences, context.mode_private);

attempting either way ensure savedusernames initialized something.

// if usernames saved, initialize savedusernames them or else initiliaze blank ready if (sharedpreferences.contains(saved_names)) { getsavedusernames(); } else { savedusernames = new arraylist<string>(); }

button listener saves current displayed username savedusernames arraylist

case r.id.bsaveusername: // add together textview text arraylist savedusernames.add(tvcurrentusername.gettext().tostring()); // addition, add together alter deletion changehasbeenmade = true; // toast feedback toast.maketext(mainscreen.this, "added list", toast.length_short).show(); break;

i have boolean goes true when each alter made. onpause()

// if there save, save if (changehasbeenmade) { toast.maketext(this, "success", toast.length_short).show(); saveusernames(); }

calling saveusernames() problem (line highlighted below)

// on pause, saveusernames private void saveusernames() { if (d) log.i(tag, "savedusernames() start"); /**** problem line ****/ string savingnamesjson = gson.tojson(savedusernames); /**** problem line ****/ // create editor, save json string , commits editor editor = sharedpreferences.edit(); editor.putstring(saved_names, savingnamesjson).commit(); if (d) log.i(tag, "savedusernames() end"); }

thanks lot time! appreciate it

android json arraylist sharedpreferences gson

No comments:

Post a Comment