3

I would like to compare string from mysql database using JSON with my string. I recieved data from database and Log shows that I have all data.

try{
     JSONArray jArray = new JSONArray(result);
     for(int i=0;i<jArray.length();i++){
         json_data = jArray.getJSONObject(i);
         Log.i("mylog","TABLE_NAME: "+json_data.getString("table_name"));//returns cars

         if (  json_data.getString("table_name") == "cars" ) { //dosent work
              .... 
         }
     }
} catch(JSONException e){
         Log.e("mylog", "Error parsing data "+e.toString());
     return false;
}

and in this example in Log I recieved name of table: cars And below IF condition doesnt work and I have no idea WHY. It is strange. I've tried many ways.

Do you know what is the reason why I cannot compare table_name from JSON with simple String?

1 Answer 1

8

Use .equals() for compare two strings in java/android.

if (json_data.getString("table_name").equals("cars")) {  

         }

it compare Strings refrence so cant work...

when You use String literal then use ==

and == only for primitive data types and here String is Object So use .equals

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you :) I just figure out this solution on other thread :)
what happens ? whats problem now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.