Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write data to local JSON file

Tags:

json

android

I have JSON file stored in assets folder. Reading from it is easy, but how can I write to it and if the data saved when exiting the app?

JSON:

{
    "Home": [
        {
            "Task": "Lapup1",
            "Time": "14:00",
            "Date": "26/12/2016"
        },
        {
            "Task": "Lapup2",
            "Time": "17:00",
            "Date": "26/12/2016"
        },
        {
            "Task": "Lapup3",
            "Time": "15:00",
            "Date": "26/12/2016"
        }
    ]
}

Json Parser (Reading):

public class JSONParser {

    ArrayList<Task> taskList;
    String json;

    public JSONParser(Context context) {
        taskList = new ArrayList<Task>();
        json = null;
        try {
            InputStream is = context.getAssets().open("Home.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void getJsonData(String type) {
        try {
            JSONObject obj = new JSONObject(json);
            JSONArray m_jArry = obj.getJSONArray("Home");

            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject jo_inside = m_jArry.getJSONObject(i);
                Log.d("DTAG", jo_inside.getString("Task"));
                Log.d("DTAG", jo_inside.getString("Time"));
                Log.d("DTAG", jo_inside.getString("Date"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

So how can I add something to my Home string?

like image 898
Dim Avatar asked Mar 29 '26 17:03

Dim


1 Answers

You can't. The assets are a read only area. To store changes you must store the file somewhere else.

like image 84
Henry Avatar answered Mar 31 '26 10:03

Henry