24

In my Android Activity I am getting a JSONArray via HTTP containg usernames. The Array looks like this:

[{"username":"Julia"},{"username":"Anja"},{"username":"Hans"},{"username":"Sophia"},{"username":"Sarah"}]

I want to check in the Android Activity if a given username already exists.

What would be the most efficient way to do it? Or do I have to iterate over the whole array?

tobias
  • 2,322
  • 3
  • 33
  • 53

1 Answers1

64

use a simple String function/method like

private boolean userexists(JSONArray jsonArray, String usernameToFind){
    return jsonArray.toString().contains("\"username\":\""+usernameToFind+"\"");
}
petey
  • 16,914
  • 6
  • 65
  • 97
  • 2
    you can also return jsonArray.toString().contains( usernameToFind ); for a cleaner and shorter solution. – ralphgabb Nov 24 '14 at 03:11
  • 17
    Sorry but this is i.m.o. a bad solution. What if a username contains partly another username? So if you have "Anja" as a username to find, but another user is called "Anjatovic". It would lead to inaccurate results. – Thermometer Dec 16 '14 at 13:39
  • 6
    @Thermometer this is why the code answer looks for start and end quotes. – petey Dec 16 '14 at 14:53
  • 3
    Woops, totally missed that, my bad! – Thermometer Dec 16 '14 at 15:01
  • 1
    Is it possible to get an Index of an object from array that has matched? – isKrishnaK Sep 27 '16 at 09:31
  • Is this an optimal solution in the case of a large array? – Vishnu G S Oct 11 '16 at 07:35
  • Whats with the downvote? https://meta.stackexchange.com/questions/135/encouraging-people-to-explain-downvotes – petey Aug 07 '17 at 21:47
  • I'm searching for a solution but IMO (IN MY OPINION) this seems not so good. What happen if the string look like `{"username": "Anja"}` or tab, or line break...? – Pham X. Bach May 09 '22 at 09:22