I'm using MPAndroidChart in my app and I'd like to save an ArrayList
in a file, for later use.
Here is where I save it to a file in the internal storage:
ArrayList<Entry> entries = getIntent().getParcelableArrayListExtra(getString(R.string.entries_key));
// Save chart data
FileOutputStream out;
try {
out = openFileOutput("listFile", MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(out);
outputStream.writeObject(entries);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
And here is where I try to retrieve it, but the returned ArrayList
doesn't contain any data and the default text ("No chart data available") in my LineChart
:
File listFile = new File(getFilesDir(), "listFile");
if(listFile.exists()) {
FileInputStream inputStream = null;
try {
inputStream = openFileInput("listFile");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// This line is evil
ArrayList <Entry> entries = (ArrayList<Entry>) objectInputStream.readObject();
// Set chart properties
chart = ChartUtils.setChartProperties(chart);
LineDataSet lineDataSet = ChartUtils.createSet(ChartViewer.this, entries);
LineData data = new LineData(lineDataSet);
chart.setData(data);
// Let the chart knows data has changed
chart.notifyDataSetChanged();
chart.invalidate();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I've doubled check it and I'm sure I'm reading in the correct file so the problem must be this line
ArrayList <Entry> entries = (ArrayList<Entry>) objectInputStream.readObject();
I found this way of reading ArrayList from file here How to write an ArrayList to file and retrieve it?
What can I do to solve this problem? Thanks