title: Out of memory error : StringBuilder.append throwing OutOfMemoryError
body: <p>I'm working on an application that fetches data from a bluetooth device. But sometimes it throws <strong>OOM error</strong> while performing some operation</p>
  
  <p>Here is the code</p>
  
  <p>The Following way I am storing the data in an <code>ArrayList&lt;String&gt;</code></p>
  
  <pre><code>private ArrayList&lt;String&gt; dataList; 
  if (response.compareTo("Some Filter") != 0 //response is of String type
  {
      dataList.add(response);
  }
  </code></pre>
  
  <p>And in the below <code>for each</code> loop it throws OOM error</p>
  
  <pre><code>for (String s : dataList) { 
  if(s.length()&gt;8)
      dataList.set(dataList.indexOf(s), s.substring(8));  
  else
      dataList.set(dataList.indexOf(s), "");
  }
  
  String downloadedData = "";
  for (String s : dataList) {
      downloadedData += s; //This one is the 280th line throwing OOM
  }
  </code></pre>
  
  <p>So far I have read <a href="https://stackoverflow.com/questions/19537550/android-out-of-memory-error-stringbuilder">this</a> post but it gives solutions for reading data in json or web response</p>
  
  <p><a href="https://stackoverflow.com/questions/4544919/android-how-to-handle-out-of-memory-exception">And i know OOM error can't be handled but prevented by following a good Architecture</a> </p>
  
  <p>And there are also these two Callbacks for Android </p>
  
  <ol>
  <li><a href="https://developer.android.com/reference/android/content/ComponentCallbacks.html#onLowMemory()" rel="nofollow noreferrer"> onLowMemory()</a></li>
  <li><a href="https://developer.android.com/reference/android/content/ComponentCallbacks2.html#onTrimMemory(int)" rel="nofollow noreferrer"> onTrimMemory()</a></li>
  </ol>
  
  <p>But i am not sure how to go for the solution !!</p>
  
  <p>The crash Stacktrace is:</p>
  
  <pre><code>java.lang.OutOfMemoryError: Failed to allocate a 106990 byte allocation with 5840 free bytes and 5KB until OOM
   at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
   java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:146)
   at java.lang.StringBuilder.append(StringBuilder.java:216) 
   at Class_name.java:280.
  </code></pre>
  
  <p>Any help is appreciated <code>:)</code></p>