3

i found a code but sometimes have error :

StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
    strHeaders.append(c);
    if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
        // end of headers
        break;
    }
}

logcat

java.lang.OutOfMemoryError
    at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
    at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:140)
    at java.lang.StringBuilder.append(StringBuilder.java:125)
    at myApp.activity.com.getFromPLS.retreiveMetadata(getFromPLS.java:98)
    at myApp.activity.com.getFromPLS.refreshMeta(getFromPLS.java:76)
    at myApp.activity.com.myApp$1.run(myApp.java:371)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    at dalvik.system.NativeStart.main(Native Method)

error on this line

strHeaders.append(c);

please any one can help me to fix this ?

0

2 Answers 2

5

Since char is an unsigned type, your while loop condition will never be satisfied, even after stream.read() starts returning -1. If you don't find a "\r\n\r\n" sequence, the loop will never end. Write the loop like this:

StringBuilder strHeaders = new StringBuilder();
int c;
while ((c = stream.read()) != -1) { // DO NOT cast to char here!
    strHeaders.append((char) c);
    final int len = strHeaders.length();
    if (len > 5 && (strHeaders.substring(len - 4)).equals("\r\n\r\n"))) {
        // end of headers
        break;
    }
}

Note that many servers will incorrectly return "\n\n" as the blank line that signals the end of the header. Some may also return "\r\r". Unless you control the server output and are guaranteed that it will see "\r\n\r\n", your blank-line detection method needs to be written in a more robust manner.

Sign up to request clarification or add additional context in comments.

Comments

0

This has more to do with the file you are reading. If the file size is large then you will landing into this issue. The best bet will be keep a check on the file size and pipe it to smaller chunks. The more you put data in StringBuffer the more loaded your memory will be.

Comments

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.