kennyYice23 kennyYice23 - 21 days ago 7x
reST (reStructuredText) Question

NegativeArraySizeException -1

I am developing an Android application that is making a call to a RESTful server through HTTP. Problem is, I am getting the following error:

NegativeArraySizeException -1
. I can't figure out why the problem is happening.

I have two classes:
. The error seems to be caused by the StringBuilder inside the HttpHelper class or that is at least where the debugger shows the cause of the exception.


public class ReadHttpTask extends AsyncTask<String, Void, CharSequence> {
protected CharSequence doInBackground(String...urls) {
String urlString = urls[0];
CharSequence result = HttpHelper.GetHttpResponse(urlString);
return result;
} catch (IOException ex){
String errorMessage = ex.getMessage() + "\n" + urlString;
Log.e("Something went wrong", errorMessage);
return errorMessage;


public class HttpHelper {

public static CharSequence GetHttpResponse(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
if(!(connection instanceof HttpURLConnection)){
throw new IOException("Not an HTTP connection");

HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK){
String responseMessage = httpConnection.getResponseMessage();
throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);

InputStream inputStream = httpConnection.getInputStream();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder(httpConnection.getContentLength());
String line = reader.readLine();
if(line==null) break;
return result;
} finally {
if(reader != null) reader.close();


You use the getContentLengthmethods from URLConnection the create an instance of StringBuilder.

First, let see the StringBuilder :

StringBuilder public StringBuilder(int capacity)

Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. Parameters:capacity - the initial capacity. Throws:NegativeArraySizeException - if the capacity argument is less than 0.

If you open the doc, you will see :


int the content length of the resource that this connection's URL references, -1 if the content length is not known, or if the content length is greater than Integer.MAX_VALUE.

So you have your solution. You should not create the StringBuilder with a specific size if this is -1, if you receive a value you can. If not, let the SB manage is own size.

Create the StringBuilder like this :

StringBuilder result = new StringBuilder(); //create with a size of 16 character.