-1

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

Evan Dix
  • 17
  • 5

1 Answers1

1

Step-1 : Create one model class of user.

public class User {
    String name;
    String id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Step-2 : Create ArrayList of model class of User.

    ArrayList<User> mArrayList = new ArrayList<User>();

Step-3 : Assuming that you know how to parse json. Set values in model in arraylist.

    try {
        JSONArray mJsonArray = new JSONArray(yourJsonString);
        for (int i = 0; i < mJsonArray.length(); i++) {
            User user = new User();
            user.setName(mJsonArray.getJSONObject(i).getString("Name"));
            user.setId(mJsonArray.getJSONObject(i).getString("id"));
            mArrayList.add(user);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

Step-4 : Here is a search function which will return id if match found.

private String searchIdByName(String name) {
    for (int i = 0; i < mArrayList.size(); i++) {
        if (mArrayList.get(i).getName().equals(name)) {
            return mArrayList.get(i).getId();
        }
    }
    return null;
}
Chitrang
  • 5,097
  • 1
  • 35
  • 58