I am parsing data of JSON that starts something like this below...
[
{"title":"dummy", "content":"ajsfhk"},
{"title":"dummy", "content":"ajsfhk"},
{"title":"dummy", "content":"ajsfhk"},
]
And my android async task class is below. But it shows that "NegativeArraySizeException
"
class RetrieveFeedTask extends AsyncTask<Object, Void, String> {
@Override
protected String doInBackground(Object... arg0) {
int responseCode = -1;
try {
URL retailerUrl = new URL("https://clients.appatlantis.com/soldy/wp-json/wp/v2/soldy-clients?_embed");
HttpsURLConnection connection = (HttpsURLConnection) retailerUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
Log.e(TAG, "Parse Data "+responseData);
} else {
Log.e(TAG, "Parse Data Failed");
}
} catch (MalformedURLException e) {
Log.e(TAG, "URL Exeption: ", e);
} catch (IOException e) {
Log.e(TAG, "IO URL Exeption: ", e);
} catch (Exception e) {
Log.e(TAG, "Exeption Caught: ", e);
}
return "Response Code "+responseCode;
}
}
And here is the exception trace
2020-04-10 15:12:31.322 27385-27449/com.appatlantis.soldy E/MainActivity: Exeption Caught:
java.lang.NegativeArraySizeException: -1
at com.appatlantis.soldy.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:149)
at com.appatlantis.soldy.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:132)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
I don't understand much about JSON.
contentLength
is -1
. Note the error:
java.lang.NegativeArraySizeException: -1
at com.appatlantis.soldy.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:149)
This tells you that you tried to initialize an array with a size of -1 on line 149, which I'm assuming based on the crash is
char[] charArray = new char[contentLength];
From the docs for getContentLength()
, this means that the content length isn't known. You should look into parsing the JSON directly from an InputStream
- it'll save you the trouble of trying to do this yourself.