Answer the question
In order to leave comments, you need to log in
RecyclerView save to JSON?
I have a recyclerview (in a fragment) and a fragment with detailed information for one of the elements. Everything would be fine, but when my data is saved. I have a bad result in my json file. Every time I open a list item or edit it is added as a new item to the JSON file when it should overwrite the old value.
Here is the ObjectJSON code:
public class ObjectJSON {
private Context mContext;
private String mFilename;
public ObjectJSON(Context context, String filename) {
mContext = context;
mFilename = filename;
}
public void saveReminders(ArrayList<Object> objects) throws JSONException, IOException {
Log.i("Save","saveReminders");
JSONArray array = new JSONArray();
for (Object f : objects)
array.put(f.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if (writer != null)
writer.close();
}
}
public ArrayList<Object> loadReminders() throws IOException, JSONException {
Log.i("Save","loadReminders");
ArrayList<Object> objects = new ArrayList<Object>();
BufferedReader reader = null;
try {
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString())
.nextValue();
for (int i = 0; i < array.length(); i++) {
objects.add(new Object(array.getJSONObject(i)));
}
} catch (FileNotFoundException e) {
//when 0
} finally {
if (reader != null)
reader.close();
}
return objects;
}
}
Answer the question
In order to leave comments, you need to log in
Try replacing Context.MODE_APPEND with MODE_PRIVATE.
Besides, it's more convenient to read like this:
ArrayList objects = new ArrayList();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question