Wednesday, May 30, 2018

json - Comparing two strings in android






Possible Duplicate:
Comparing two identical strings with == returns false






I am having real hard time with solving this code. This might look silly but I am not able to figure out what is happening. I am parsing a JSONArray(No big deal!) I am traversing the array with a for loop. I want to break the loop when the user input and the value matches. Here is my code



String regi = null;
JSONObject studentObject = null;
try {

JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}

course = studentObject.getString("COURSE_CODE");
Log.d("Details", name + course + regi + i);//Out put: nullGraduate081018394:name - null
//course: Graduate (same for all), regi: last registration number,
//i: giving totalnumber of objects


As per my knowledge the loop should stop when it finds a match. The COURSE_CODE will be corresponding to the student. Am I missing something?



Please note: The function getInternetData() is returning the whole JSON Array. The loop is completely traversing every object.


Answer




Strings cannot be compared with == in Java. You have to use string1.equals(string2).


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...