N
N
Nick20152015-12-07 20:29:25
Android
Nick2015, 2015-12-07 20:29:25

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;
    }
}

Here's how it does it for me:
5wSZi.png
RecyclerView saving in JSON
If this is a spelling error, I can provide the code here is the link . Or I can throw the rest here.
Please tell me what is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Farber, 2015-12-17
@afarber

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 question

Ask a Question

731 491 924 answers to any question