Reputation: 111
Basically I want to convert a JSONObject json into an integer (127181078). When I use this code:
int intOfReceivedID = Integer.parseInt(json);
I get this error message:
java.lang.NumberFormatException: Invalid int: 127181078"
When I use this code:
char[] charArray = json.toCharArray();
String stringCharArray = charArray.toString();
testTextView.setText(stringCharArray);
testTextView gives me: [C@2378e625
However, when I use this code:
preprocessedjson = String.valueOf(json);
testTextView.setText(preprocessedjson);
The TextView
gives 127181078, but I get the some error when I parse the text to an integer.
This is the php code:
$myfile = fopen($filename, 'r') or die("Unable to open file!");
echo fread($myfile,filesize($filename));
fclose($myfile);
This is the the makeHttpRequest:
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
Upvotes: 0
Views: 652
Reputation: 10095
int intOfReceivedID = Integer.parseInt(json);
I get this error message:
java.lang.NumberFormatException: Invalid int: 127181078"
This happens because there is a new-line character at the end of the ID which can not be parsed into an Integer.
When I use this code:
char[] charArray = json.toCharArray(); String stringCharArray = charArray.toString(); testTextView.setText(stringCharArray);
testTextView gives me: [C@2378e625
By default, calling toString()
on an object prints the memory location of the object (in this case [C@2378e625
). That's what's being displayed in the TextView
.
However, when I use this code:
preprocessedjson = String.valueOf(json); testTextView.setText(preprocessedjson);
The TextView gives 127181078, but I get the some error when I parse the text to an integer.
You'll get an error when parsing the text to an integer because it still has an invalid new-line character at the end.
If you are receiving a JSONObject
from the server which only contains a long, then you can use the getLong()
or optLong()
methods to retrieve the integer value. The JSON parser automatically handles all the parsing and you don't need to do any additional work.
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
final long receivedId = json.optLong();
Upvotes: 0
Reputation: 5289
This question is confusing but from your error message it looks like this is a Java question that has nothing to do with JSON since your json String in this case looks like it does not in fact contain json(from the exception message).
It looks like the issue is your json value is a number plus additional spaces which Integer.parseInt does not handle.
Try
Integer.parseInt(json.trim())
Upvotes: 2