0

So I am using the MPandroid chart dependency to plot the graph on an android app. For this I am adding data to an ArrayList of class Entry of the graph. I am adding the data manually for now but I want to parse a the data from a json file and add it to graph. can anyone tell me how can I read individual data elements of Json array to add to graph.

This is the code I am using to read the json file.I have the file in my asset folder.

  try {
        InputStream is=getAssets().open("gaitdata.json");
        int size=is.available();
        byte[] buffer=new byte[size];
        is.read(buffer);
        is.close();
        json=new String(buffer,"UTF-8");
        JSONArray jsonArray=new JSONArray(json);

            for(int i=0;i<jsonArray.length();i++){
                JSONObject obj=jsonArray.getJSONObject(i);
                if(obj.getString("name").equals("kinematics")){
                    hipvalue.add(obj.getString("hip_min"));


              }
            }

Also this is the json file I want to read.

{
 "name":"kinematics",
 "hip_min":[1.2,5.67,2.34,6.8]
}

Also I want the float value but since it is not working so I have used obj.getString() to get the "hip_min" value for json.

And Lastly this is how I add data manually to Array list.

ArrayList<Entry> entries=new ArrayList<>();
        entries.add(new Entry(0,19.85f));

1 Answer 1

0

For converting the Json Arry to floating Array you can try the following code .

   String value = "{'name':'kinematics','hip_min':[1.2,5.67,2.34,6.8]}";
        JSONObject obj = new JSONObject(value);
        List hip_min = new ArrayList<Float>();
        JSONArray jsonArray;

        jsonArray = obj.getJSONArray("hip_min");

        for (Object item : jsonArray
        ) {
            hip_min.add(item);
        }
        System.out.println("Size : " + hip_min.size());

And for Chart

 int i=0;
        for (Object item:hip_min
             ) {
            entries.add(new Entry(i,item))
                    i=i+2;


        }

the value of i is for horizontal shift. i hope that will help.

Sign up to request clarification or add additional context in comments.

2 Comments

the part: for(Object item : jsonArray) give me error as "foreach not applicable to type 'org.json.JSONArray'. What shall I do?
Ok I will try it!!

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.