raco raco - 1 year ago 57
Java Question

JSON will load just one value

Well problem is while JSON reads file in load method. I will describe in the coments.
NOTE: many code is omitted for more clear view

private static final String ID = "moti_data";

public static void save(Context context) throws IOException, JSONException {
JSONArray arr = new JSONArray();
JSONObject obj = new JSONObject();
for (int i = 0; i < notify1.length; i++)
obj.put("n1_" + i, notify1[i]);
//while testing ar.toString() was arr[{"n1_0":1,"n1_1":15,"n1_2":23,"n1_3":0}]
//it is clear that it contains 4 values but arr.length() will give 1
String file = arr.toString();
FileOutputStream output = context.openFileOutput(ID, MODE_PRIVATE);

then problems persists in load method since i can get just one value out of it. Also all others values are incorrect - 0. So when i have managed to make it word for few minutes output was arr[{"n1_0":1,"n1_1":0,"n1_2":0,"n1_3":0}]. S0 just first value is correct

public static void load(Context context) throws IOException, JSONException {
//reading data
FileInputStream input = context.openFileInput(ID);
BufferedInputStream bi = new BufferedInputStream(input);
StringBuffer buffer = new StringBuffer();
while (bi.available() != 0) {
char c = (char) bi.read();
JSONArray data = new JSONArray(buffer.toString());
for (int i = 0; i < data.length(); i++)
notify1[i] = data.getJSONObject(i).getInt("n1_" + i);

So whatever i do/have tried i get one loop and json exception. But as i initialy tought problem is not in saving since outputs were good. Or am i wrong?

EDDIT: there are 6 blocks of 4 values in code (here is just one for clarity). Also i cant hardcode them since values are ment to be changed by the user

Answer Source

Your JSONArray only contains one JSONObject:

 { "n1_0":1,
 } //finish data.getJSONObject(0);

To access to every value on the JSONObject you should do:

JSONObject object = data.getJSONObject(0);
for (int i = 0; i < data.length(); i++)
    notify1[i] = object.getInt("n1_" + i);

I use https://jsonformatter.curiousconcept.com to see the JSON hierarchy in a clear way. Hope I solved your problem.