Android: JSON string data compare with other string

android, compare, json, string

Solution

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`

Problem

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?

Original source