Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialharry zeng
5,911 PointsException caught
I wrote the same code in the video on Android Studio but when i run it, the logcat says exception caught: org.json.JSONException: Unterminated string at character 5822 of {…………………………………………. when i try to put more logs, i see that the exception is thrown by JSONObject jsonRsponse=new String(charArray), What is the problem? ThankS!
1 Answer
Harry James
14,780 PointsHey Harry! (Same name :o)
Hubert Maraszek has a great fix for this, I'll include it here:
Delete these lines:
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
Replace them with these:
int nextCharacter; // read() returns an int, we cast it to char later
String responseData = "";
while(true){ // Infinite loop, can only be stopped by a "break" statement
nextCharacter = reader.read(); // read() without parameters returns one character
if(nextCharacter == -1) // A return value of -1 means that we reached the end
break;
responseData += (char) nextCharacter; // The += operator appends the character to the end of the string
}
This worked for me and many other users so, I think it should work for you also :) Be sure to give Hubert credit for this by giving him a positive rating if it fixed your problem! You can do so here (Hubert is the second answer).
erlanggasatria
4,867 Pointserlanggasatria
4,867 PointsDo you mind to explain what's wrong with using reader.read(charArray) ?
Harry James
14,780 PointsHarry James
14,780 PointsIt's very technical but Ben was talking about it over here and here. The reason being is that the char array gets malformed sometimes from special characters being used - I believe it's dollar signs that are causing the bug (This bug may have been resolved now, though) and/or if a content-length value is not returned from the HTTP page (If it isn't, it's value will be set to -1 and, it's not possible to make an array -1 in size...).
The fix will actually ignore the content-length part so, whether a website provides one or not, it should not matter.