kennyYice23 kennyYice23 - 2 months ago 12
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:
ReadHttpTask
and
HttpHelper
. 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.

ReadHttpTask:

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


HttpHelper:

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;
try{
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder(httpConnection.getContentLength());
while(true){
String line = reader.readLine();
if(line==null) break;
result.append(line);
}
return result;
} finally {
if(reader != null) reader.close();
}
}
}

Answer

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 :

Returns

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.
Comments