0

I want to store boolean arraylist in local file and load values in onCreate(). I'm using

public void saveBoolean(String fileName, ArrayList<Boolean> list){
    File file = new File(getDir("data", MODE_PRIVATE), fileName);
    ObjectOutputStream outputStream = null;
    try {
        outputStream = new ObjectOutputStream(new FileOutputStream(file));
    } catch (IOException e) {
        //
    }
    try {
        outputStream.writeObject(list);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
        //
    }
    try {
        outputStream.close();
    } catch (IOException e) {
        //
    }
}

and

private ArrayList<Boolean> getSavedBooleanList(String fileName) {
    ArrayList<Boolean> savedArrayList = new ArrayList<>();

    try {
        File file = new File(getDir("data", MODE_PRIVATE), fileName);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        savedArrayList = (ArrayList<Boolean>) ois.readObject();
        ois.close();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    return savedArrayList;
}

but it invokes NullPointerExcpetion when attempt to initialize custom view listview. I'm also saving and loading string and integer lists like this, string list is loaded but integer and boolean lists are not initialized so length is 0 and my code loading value at listview position so it invokes error because length is 0 while inxed is for example 2. Is here any way to save/load integer and boolean list into file or I must convert booleans and integers into string before saving? Thanks for every reply.

Martin
  • 652
  • 9
  • 27

1 Answers1

0

Alternate to your method is saving in shared preferences

here you go :

 private void saveToSharedPreference(ArrayList<Boolean> arrayList) {
    Gson gson = new Gson();
    SharedPreferences sharedPreferences = this.getSharedPreferences("Test", Context.MODE_PRIVATE);
    sharedPreferences.edit().putString("ArrayList", gson.toJson(arrayList)).commit();
}

private ArrayList<Boolean> getSharedPreference() {
    Gson gson = new Gson();
    SharedPreferences sharedPreferences = this.getSharedPreferences("Test", Context.MODE_PRIVATE);
    String booleanString = sharedPreferences.getString("ArrayList", null);
    TypeToken<ArrayList<Boolean>> typeToken = new TypeToken<ArrayList<Boolean>>() {
    };
    ArrayList<Boolean> booleen = gson.fromJson(booleanString, typeToken.getType());
    return booleen;
}
vikas kumar
  • 10,447
  • 2
  • 46
  • 52
  • just fast note: compile 'com.google.code.gson:gson:2.8.2' have to be added but it works, thanks – Martin Nov 11 '17 at 18:54