Handling large strings in Android (OutOfMemeryError)
<p>I am currently working on an Android application and has encountered an OutOfMemoryError on a Motorola Defy. </p>

<p>The place where the error occurs, is where I convert a 5MP image to a Base64 encoded string which subsequently is sent to a web service contained in a SOAP document. </p>

<p>I am aware, that both the actual encoding of the image, and using SOAP both are overheads - and would prefer myself to eliminate those - but that is not possible right now. </p>

<p>My question goes more on how to handle the large strings, being not to much into Java and Memory handling I need a little assistance. </p>

<p>The code is approx like this: </p>

<pre><code>String soapMessage = registration.createSoapRequest();
//In this method a StringBuilder is used to build the message, and returns it 
//as new String(soap.toString();

//At this point I have to objects in memory using approx 6 and 9 MB each.
//I would expect it to be the StringBuilder and the string soapMessage. 
//But I can't figure out how to GC the StringBuilder - which I don't need to use 
//any more.

//Declaring the entity to post
StringEntity entity = new StringEntity(soapMessage, HTTP.UTF_8);

//By declaring the entity, I receive my OutOfMemoryException, due to having 
//the 6-7 MB string now replicated 3 times - giving 21 MB alone. 

entity.setContentType("text/xml");

//Creating client
HttpClient client = new DefaultHttpClient();

HttpPost post = new HttpPost("http://MYSERVER/services/registration.svc");
post.setHeader("Content-Type","text/xml; charset=utf-8");
post.setHeader("SOAPAction", "http://tempuri.org/IRegistration/PostRegistration");

post.setEntity(entity);

BasicHttpResponse response = (BasicHttpResponse)client.execute(post);
</code></pre>

<p>The obvious Memory issue here seems to make me able to only hold one instance of the string in memory. </p>

<p>How would I do this?</p>

<p>I hope somebody can help me through this as I feel stuck in Java Memory handling.</p>

<p>Best regards
/Anders</p>
