So I make a request to my online api, I get the correct response, but when its time to compare the values from the response, I get a logical error as the default 'else' statement is been executed and the toast i get is "Unknown Error!" instead of the 'if' statement for code:200. PLease help out.
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String code = jsonObject.getString("code");
if (code=="200"){
String UserID=jsonObject.getString("id");
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, UserID, duration);
toast.show();
}
else if (code=="201"){
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Account Not Found!", duration);
toast.show();
}
else{
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Unknown Error!", duration);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, e.toString(), duration);
toast.show();
}
}
CodePudding user response:
The problem is highly likely due to the comparison of strings with =
. Always use String.equals()
when comparing strings:
if (code.equals("200")) {
String UserID = jsonObject.getString("id");
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, UserID, duration);
toast.show();
} else if (code.equals("201")) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Account Not Found!", duration);
toast.show();
} else {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Unknown Error!", duration);
toast.show();
}
Also see this answer.