Saving and Reading an ArrayList

67
June 19, 2017, at 02:30 AM

Saving method(save list is an Arraylist)-

public static void saveList(){
    editor.putString("list", Calculate.saveList.toString());
}

my reading methos (probably where my problem is)-

public static void readList(){
    String arrayString= prefs.getString("list", null);
    Calculate.saveList = (ArrayList<String>) Arrays.asList(arrayString.split(","));
}

logcat error-

                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tsury.icalorie/com.tsury.icalorie.SavedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference

Thanks in Advance to all of you.

I need to save that ArrayList and of course reading it later.

Answer 1

Make sure you are calling .apply() or .commit() on your editor object when saving.

You also cannot cast Arrays.asList() to an ArrayList, you should create it with

Calculate.saveList = new ArrayList<String>(Arrays.asList(arrayString.split(",")));
Answer 2

you can convert your array list to json string and save it as string and read that json string and convert it to your object.

you can use Gson library to do that.

do this steps:

1- add this dependancy in your Gradle file

compile 'com.google.code.gson:gson:2.7'

make a class that keep your ArrayList

class MyList{
   @SerializedName("myStrings")
   public ArrayList<String> myStrings;
}

create an instance of MyList class and add string your values in myString. then conver your MyList object to Json using this line:

String json=new Gson().toJson(myListInstance)

and save this json String in sharedPreferences

when you want to load your data read your json string from sharedPreferences and then convert it to your object using this line

MyList myList = new Gson().fromJson(json, MyList.class);
READ ALSO
Show confirm dialog in Flux architecture

Show confirm dialog in Flux architecture

I'm trying to understand Flux architectureI'm using JavaFX and the FluxFX experimental framework

66
How to Compare a String with a Char

How to Compare a String with a Char

Guys how do i compare a String with a char ? heres my code :

63
What&#39;s wrong with my main method, and why is it throwing this exception? [on hold]

What's wrong with my main method, and why is it throwing this exception? [on hold]

I'm a new Java developer, writing my first real Java application, which is a calendar viewerHere's the code I wrote which is indicated as having errors:

79
Need to change the background of a TabbedPane in swing and backgroundColor of a panel

Need to change the background of a TabbedPane in swing and backgroundColor of a panel

Please find the imageI marked one tab which is colored blue

56