title: How to calculate average value using List of doubles from database
body: <p>I am trying to calculate an average value from a list of doubles I get from my database using the method explained in <a href="https://stackoverflow.com/a/10466020/1617602">this post</a> but it doesn't work. The app crashes probably because of an overflow.</p>
  
  <pre><code>private double getAverage() {
          Cursor cursor = db.getMarks(subject);
          List&lt;Double&gt; list = new ArrayList&lt;Double&gt;();
          cursor.moveToFirst();
          while(!cursor.isAfterLast()) {
              list.add(cursor.getDouble(cursor.getColumnIndex(DBAdapter.KEY_VALUE)));
          }
          if (list.isEmpty())
              return 0.0;
  
          long sum = 0;
          int n = list.size();
          for (int i = 0; i &lt; n; i++)
              sum += list.get(i);
          return ((double) sum) / n;
      }
  </code></pre>
  
  <p>Is there a method to get a working code for calculating the average?
  Thanks in advance</p>