s3yfullah
s3yfullah

Reputation: 165

JSONObject getString if statements

String result = "{\"error_type\":\"success\",\"message\":\"Error Message....."}";

JSONObject json = new JSONObject(result);
if( (json.getString("error_type") == "error") {
   Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
} else {
   Toast.makeText(getApplicationContext(), "Nooo", Toast.LENGTH_LONG).show();
}

This code is Toasting "Nooo". But json.getString("error_type") is a "error". What is this problem ?

Upvotes: 0

Views: 1943

Answers (1)

Jonathan Fretheim
Jonathan Fretheim

Reputation: 902

You should test String equality using the equals method instead of ==. i.e.,

if (json.getString("error_type").equals("error")) {
  ...
}

the == operator compares object references and not the contents of the String itself.

Upvotes: 4

Related Questions