Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Evan Dix
1,641 PointsSeeing if text put into an edit text is equal to the name of a person in a JSONArray.
I have an jsonarray of names and an Id for each name. For example
[{ "Name":"Evan" , "id":1},{"Name":"Aaron","id":2}ect....]
if i have an edit text, that the user types in a name. How can i create a loop to pass through the array and return the id of the person's name that they typed in if there is a match.
so if they type in Evan into the edit text. i want the app to Log the id: 1
1 Answer
elfproductivity
10,489 PointsString name = yourEditTextVariableName.getText().toString();
int id = -1; //some untaken value by the id to check against later (in case we didn't find it), if there's no such value, use a boolean flag
for (JSONObject person : JSONArray) { //loop through the array
if (person.getString("Name").equals(name)) { //if this person has the name entered by the user
id = person.getInt("id");
}
}
if (id == -1) {
//not found
} else {
//do something with id
}
This is assuming that the "Name" field values will be unique, if not, it will just give you the ID of the last person with this name in the array. An alternative would be to create an a list object to add each person's ID into.
Evan Dix
1,641 PointsEvan Dix
1,641 PointsThank you! this will help me get on the right track