开发者

Handling large strings in Android (OutOfMemeryError)

开发者 https://www.devze.com 2023-02-15 00:52 出处:网络
I am currently working on an Android application and has encountered an OutOfMemoryError on a Motorola Defy.

I am currently working on an Android application and has encountered an OutOfMemoryError on a Motorola Defy.

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.

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.

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.

The code is approx like this:

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);

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

How would I do this?

I hope somebody can help me through th开发者_运维问答is as I feel stuck in Java Memory handling.

Best regards /Anders

0

精彩评论

暂无评论...
验证码 换一张
取 消