1

Am having an arraylist

 ArrayList<HashMap<String, String>> arraylist;

and am adding json data to this arraylist to populate in listview later, using hashmap in the below format

                   int ja=jsonarray.length();

            for (int i = 0; i <= ja; i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects

                map.put("slno", jsonobject.getString("slno"));
                map.put("mark", jsonobject.getString("mark"));


                // Set the JSON Objects into the array
                arraylist.add(map);

            }

the problem is I want to calculate all the mark values and populate in a textview as total marks. how shall I achieve this?

2 Answers 2

2

This might not be the best way to do, but it will definitely give you the solution.

try{
   int sum = 0;
   for(HashMap<String, String> map : arrayList) {
      sum += Integer.parseInt(map.get("mark"));
   }
} catch (Exception e) {
   //Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Sign up to request clarification or add additional context in comments.

4 Comments

am getting 0 as output
Could you please post your complete code in your question. Also could you check if you are getting back values for the marks in the JSON?
am getting value of marks.. shall i use your solution inside arrayadapter or in postexecute?
sorry!!! it worked. due to float numbers may be it was not showing the desired result.. thanks
1

I think you just need to go through the ArrayList and find the "mark" key from your HashMap and add it to the total sum.

    int nTotalSum = 0;

    try
    {

      for( int i =0; i < arraylist.size(); i++ )
      {
        HashMap<String, String> map = arraylist.get(i);
        String sValue;
        if ( (sValue=map.get("mark")) != null)
        {
          nTotalSum += Integer.parseInt(sValue);
        }
      }
    }
    catch (Exception e)
    {
    }
    System.out.println("Total Mark: " + nTotalSum);

2 Comments

shall i use this inside postexecute or in arrayadapter?
you can use it either. it really depends on how big is the size of your ArrayList. If it is less than 100 then you can put it anywhere but if you will be processing many entries like thousands then a Thread or in the doInBackground might be a good choice.

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.