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?

0

1 Answer 1

64

use a simple String function/method like

private boolean userexists(JSONArray jsonArray, String usernameToFind){
    return jsonArray.toString().contains("\"username\":\""+usernameToFind+"\"");
}
Sign up to request clarification or add additional context in comments.

8 Comments

you can also return jsonArray.toString().contains( usernameToFind ); for a cleaner and shorter solution.
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 this is why the code answer looks for start and end quotes.
Woops, totally missed that, my bad!
Is it possible to get an Index of an object from array that has matched?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.