android - Strange results!!! Is it because of json? or what? -


i have class called grademodel2 has 2 members: grade (as string) , sections (as list of strings). trying grademodel2s data json string i've read server.

list<grademodel2> gradelist = new arraylist<>(); list<string> sectionslist = new arraylist<>(); jsonobject jo = new jsonobject(json); jsonarray grades = jo.getjsonarray("grades"); (int i=0;i<grades.length();i++){     sectionslist.clear();     jsonobject grade = grades.getjsonobject(i);     jsonarray sections = grade.getjsonarray("sections");     log.e("length",sections.length()+"");     (int k=0;k<sections.length();k++)         sectionslist.add(sections.getstring(k));     gradelist.add(new grademodel2(grade.getstring("grade"), sectionslist)); } /**************/ (grademodel2 grade : gradelist) {     list<string> ss = grade.getsections();     (string s : ss)         log.e("section",grade.getgrade()+" : "+s); } /**************/ 

the retrieved json string looks following:

{"id":"596","privileges":"t","grades":[{"grade":"1","sections":["a","b","c"]},{"grade":"3","sections":["a","b"]},{"grade":"7","sections":["a"]},{"grade":"9","sections":["b"]},{"grade":"10","sections":["a"]}]} 

the problem sections list of grademodel2 objects of length 1 , value a !!! first log.e, 1 line before inner loop, shows length of first item of list 3 (a,b, , c (see json)). however, trying print sections of each grademodel2 object in inner loop in second block, see section a grades!!! (see pic)

the result of 2 log.e

what going on? why happening?

your problem in sectionslist. trying reuse same object, line of code new grademodel2(..., sectionslist); add reference same sectionslist. , because of sectionslist.clear(); see "a" last json section ({"grade":"10","sections":["a"]}) fix this, have create new array each time in loop. this:

for (int = 0 ; < grades.length() ; i++){     list<string> sectionslist = new arraylist<>();     // ... json code here     gradelist.add(new grademodel2(grade.getstring("grade"), sectionslist)); } 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -