Android Invalid Int error when parsing number from text file - java

I have a .txt in my website that contains a number (in this case 3) and I use this code to check whether this number is greater than or less than another number, but the code gives me this error:
03-03 16:27:43.734: E/AndroidRuntime(16318): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.downloadingprogressbar/com.example.downloadingprogressbar.MainActivity}: java.lang.NumberFormatException: Invalid int: "3
This is my code:
HttpGet httppost = new HttpGet("http://mywebsite.org/version.txt");
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String casa = new String(total.toString());
//boolean version = (casa>4);
if (Integer.parseInt(casa)>4){
risposta.setText("la tua versione è aggiornata");
}
else {
risposta.setText("aggiorna la tua versione");
}

I agree with Kon, your variable "casa" is containing another characters.
Try using the trim() method:
if (Integer.parseInt(casa.trim())>4){
...
...
...
but now i see that you are appending the "\n", in total variable, is this "new line" necessary?:
while ((line = r.readLine()) != null) {
total.append(line);
}

Try this to remove all whitespace that might be surrounding your number:
if (Integer.parseInt(casa.trim()) > 4){
// ...
}

Related

How to parse this provided XML with java.xml.xpath?

I am trying to parse this XML:
<?xml version="1.0" encoding="UTF-8"?>
<veranstaltungen>
<veranstaltung id="201611211500#25045271">
<titel>Mal- und Zeichen-Treff</titel>
<start>2016-11-21 15:00:00</start>
<veranstaltungsort id="20011507">
<name>Freizeitclub - ganz unbehindert </name>
<anschrift>Macht los e.V.
Lipezker Straße 48
03048 Cottbus
</anschrift>
<telefon>xxxx xxxx </telefon>
<fax>0355 xxxx</fax>
[...]
</veranstaltungen>
As you can see, some of the texts have whitespace or even linebreaks. I am having issues with the text from the node anschrift, because I need to find the right location data in a database. Problem is, the returned String is:
Macht los e.V.Lipezker Straße 4803048 Cottbus
instead of:
Macht los e.V. Lipezker Straße 48 03048 Cottbus
I know the correct way to parse it should be with normalie-space() but I cannot quite work out how to do it. I tried this:
// Does not work; afaik because xpath 1 normalizes just the first node
xPath.compile("normalize-space(veranstaltungen/veranstaltung[position()=1]/veranstaltungsort/anschrift/text()"));
// Does not work
xPath.compile("veranstaltungen/veranstaltung[position()=1]/veranstaltungsort[normalize-space(anschrift/text())]"));
I also tried the solution given here: xpath-normalize-space-to-return-a-sequence-of-normalized-strings
xPathExpression = xPath.compile("veranstaltungen/veranstaltung[position()=1]/veranstaltungsort");
NodeList result = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
String normalize = "normalize-space(.)";
xPathExpression = xPath.compile(normalize);
int length = result.getLength();
for (int i = 0; i < length; i++) {
System.out.println(xPathExpression.evaluate(result.item(i), XPathConstants.STRING));
}
System.out prints:
Macht los e.V.Lipezker Straße 4803048 Cottbus
What am I doing wrong?
Update
I have a workaround already, but this can't be the solution. The following few lines show how I put the String together from the HTTPResponse:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName(charset)))) {
final StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// stringBuilder.append(line);
// WORKAROUND: Add a space after each line
stringBuilder.append(line).append(" ");
}
// Work with the red lines
}
I would rather have a solid solution.
Originally, you seem to be using the following code for reading the XML:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName(charset)))) {
final StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
This is where your newlines get eaten: readline() does not return the trailing newline characters. If you then parse the contents of the stringBuilder object, you will get an incorrect DOM, where the text nodes do not contain the original newlines from the XML.
Thanks to the help of Markus, I was able to solve the issue. The reason was the readLine() method of the BufferedReader discarding line breaks. The following codesnippet works for me (Maybe it can be improved):
public Document getDocument() throws IOException, ParserConfigurationException, SAXException {
final HttpResponse response = getResponse(); // returns a HttpResonse
final HttpEntity entity = response.getEntity();
final Charset charset = ContentType.getOrDefault(entity).getCharset();
// Not 100% sure if I have to close the InputStreamReader. But I guess so.
try (InputStreamReader isr = new InputStreamReader(entity.getContent(), charset == null ? Charset.forName("UTF-8") : charset)) {
return documentBuilderFactory.newDocumentBuilder().parse(new InputSource(isr));
}
}

Getting an exception when putting string before while

I am using the following code to get data from a file
try {
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput(TEXTFILE));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String string;
StringBuilder stringbuilder = new StringBuilder();
while ((string=bufferedReader.readLine())!=null){
stringbuilder.append(string);
}
EditText.setText(stringbuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
It works but
when I put the string=bufferedReader.readLine() before While, I get an exception : java.lang.OutOfMemoryError
You're reading a line from the BufferedReader, and storing the result in string. After that, you check if string != null, and if not, you append string to stringbuilder. You're repeating this until string == null.
The confusion here might be the comparison of an assignment statement:
while ((string = bufferedReader.readLine()) != null) { ... }
This is a short notation of the following:
string = bufferedReader.readLine();
while (string != null) {
...
string = bufferedReader.readLine();
}

php - parse single value to android

I try to write a simple php file, which checks, whether a mysql value exists or not.
For this, I need to parse a simple string from json to android.
e.g: when the value exists, the string is "yes" and when it doesnt exists the string is "no".
Meanwhile I have tried a lot of "solutions", but nothing works.
To do that I usually use this:
$abfrage = "
SELECT
Something
FROM
somewhere
WHERE
This=$that"
;
$link = mysql_query($abfrage) OR die("Error:"+mysql_error());
while($line = mysql_fetch_assoc($link)){
$new=$line;
}
print(json_encode($new));
and in Android:
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
System.out.println(result);
json_data = new JSONObject(result);
String name=(json_data.getString("something"));
Log.e("pass 3", "connection success ");
}
catch(Exception e)
{
Log.e("result:", result.toString());
}
}
This works well, an the the value of the String "name" is the value of "something".
But now my question:
Is it possible to save a string in PHP and parse them to android?
This is what i got:
$abfrage = "SELECT Something FROM somewhere WHERE This = '$that' LIMIT 1";
// Proof whether the value exists or not
$read = mysql_db_query($db, $abfrage);
if (mysql_num_rows($read) == 0){
$value="no";
}
else{
$value="yes";
};
print json_encode($value);
And in JAVA:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/test.php");
HttpResponse response = httpclient.execute(httppost);
String str = EntityUtils.toString(response.getEntity());
System.out.println(""+str); //prints: yes
if(str=="yes") System.out.println("ok"); //not called
if(str=="no") System.out.println("nope"); //not called
I am not sure how you implemented it, but I assume that you execute PHP script from java code with something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample/sample.php");
HttpResponse response = httpclient.execute(httppost);
Then simply use:
String str = EntityUtils.toString(response.getEntity());
Use
Log.d("Title", "Message");
To display messages in Logcat console.
I faced this problem months before:
The problem is, that the String str, not only contains the word "yes". It also contains different letters/symbols, which are not displayed in Android/Eclipse. So you have to manually delete these letters by simply calling substring(int start, int end)
Try this:
String str = EntityUtils.toString(response.getEntity());
int number= str.length();
System.out.println("str-length"+number); //You will see not the length of 3 (for yes)
String s2= str.substring(0, 3); //short the string
System.out.println("String s2"+s2);
if(s2.equals("yes"))Log.d("Titles", str);

Get .txt file and parse it by new line or comma

I have a .txt file in this format:
file.txt (each line has text)
text1
text2
longtext3
...
..
I am downloding it:
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = newBufferedInputStream(connection.getInputStream());
How can I parse this input so I get the text in each new line?
I tried something like that:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
} }
but I don't want to save it,so I don't have the File instance
I can save in this format:
text1,text2,longtext3,....
If its more simple to extract it
You can use an InputStreamReader (http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html).
Put it between your InputStream and your BufferedReader. Now you don't need the File instance (and so there is no need to save it first).
Something like ...
InputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
// further break the line into a list of comma separated values
List<String> commaSeparatedValues = Arrays.asList(line.split(","));
}
...
You can use the Scanner class
String result = "";
Scanner in = new Scanner(new FileInputStream(file));
while(in.hasNextLine())
result += in.nextLine() + ",";
this will create a string like this:
text1,text2,longtext3,....
I'm not sure what you're asking but I think you want to save each line of a text file. This worked for me, it puts every line into one long string.
public static void main( String[] args )
{
String FILE_URL = "http://www.google.com/robots.txt";
String FILE_CONTENTS = "";
try
{
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
while( line != null )
{
FILE_CONTENTS += line;
line = reader.readLine();
}
}
catch( MalformedURLException e )
{
System.out.println("Malformed URL" );
}
catch( IOException e )
{
System.out.println( "IOException" );
}
}
Try to scan as normal text and replace every '\n' in a comma...

Removing characters from a string

I have an app in which I parse a .txt file from a URL and spit out the string to the user. I want to remove the first 16 characters of the string. How can I do this?
EDIT- I want to remove 16 characters from the data I receive from my http call.
public void onClick(View src) {
switch(src.getId()) {
case R.id.buttonRetrieveMetar:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EditTextAirportCode.getWindowToken(), 0);
textDisplayMetar.setText ("");
airportcode = EditTextAirportCode.getText().toString();
url = urlmetar + airportcode + ".TXT";
//Added 06-27-11 METAR code
textDisplayMetar.setText ("");
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
BufferedReader r = new BufferedReader(new
InputStreamReader(content));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
textDisplayMetar.append("\n" + total + "\n");
} catch (Exception e) {
//handle the exception !
}
break;
Thanks!
You can't modify the string itself, but you can create a substring easily enough:
line = line.substring(16);
The single-parameter overload of substring takes the whole of the rest of the string after the given start index. The two-parameter overload starts at an index specified by the first argument, and ends at an index specified by the second argument (exclusive). So to get the first three characters after "skipping" the first 16, you'd use:
line = line.substring(16, 19);
Note that you don't have to assign back to the same variable - but you need to understand that it doesn't affect the string object that you call it on. So:
String original = "hello world";
String secondPart = original.substring(6);
System.out.println(original); // Still prints hello world
System.out.println(secondPart); // Prints world
EDIT: If you want to remove the first 16 characters of the whole file, you want:
textDisplayMetar.append("\n" + total.toString().substring(16) + "\n");
If you want that on a per-line basis, you want:
while ((line = r.readLine()) != null) {
total.append(line.substring(16));
}
Note that both of these may require extra validation - if you call substring(16) on a string with less than 16 characters, it will throw an exception.
Try this:
String newString = oldString.substring(16);

Categories

Resources