1

I am trying to extract some data from a json array file, i followed the steps from Reading a Json Array in android

a snippit of the json array:

[
{
"JobNo": 1,
"JobTime": 30,
"JobDate": "20170911",
"WorkerTime": 27,
"JobTimeError": -3
},
{
"JobNo": 2,
"JobTime": 22,
"JobDate": "20170911",
"WorkerTime": 21,
"JobTimeError": -1
},

What i want to be able to do is, extract the data and store them into their own arrays, JobNo to JobNo array, etc. the following code is my attempt, but it doesn't store the values (crashes at toast because it says no data in array). thanks

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
    ArrayList<Integer> JobNo = new ArrayList<>();
    ArrayList<Integer> JobTime= new ArrayList<>();
    ArrayList<String> JobDate= new ArrayList<>();
    ArrayList<Integer> WorkerTime= new ArrayList<>();
    ArrayList<Integer> JobTimeError = new ArrayList<>();

    try {
        JSONObject json = new JSONObject(loadJSONFromAsset());
        JSONArray jArray = json.getJSONArray("Data");

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);
            int JobN = json_data.getInt("JobNo");
            int JobT = json_data.getInt("JobTime");
            String JobD = json_data.getString("JobDate");
            int WorkT = json_data.getInt("WorkerTime");
            int JobTE = json_data.getInt("JobTimeError");
            JobNo.add(JobN);
            JobTime.add(JobT);
            JobDate.add(JobD);
            WorkerTime.add(WorkT);
            JobTimeError.add(JobTE);

        }
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    Toast.makeText(this,
            JobDate.get(1),
            Toast.LENGTH_LONG).show();
}

    public String loadJSONFromAsset() {
    String json = null;
    try {

        InputStream is = getAssets().open("convertcsv.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();
        return null;
    }
    return json;

}

1 Answer 1

2

Your JSON String is not a JSON object, it is a JSON Array, So use:

JSONArray jArray = new JSONArray (loadJSONFromAsset());
Sign up to request clarification or add additional context in comments.

1 Comment

Sometimes mistakes happen. Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.