Basically I have a textbox and an edittext box that looks like this:
Username [ ]
Then at the bottom there is a button called "Submit".
Simply enough, I have to type in a username, compare it to a string array that I have in my strings.xml file, and if it does not equal any of the strings in the array, then I am good to go.
The string array looks like this:
<string-array name="usernames">
<
item>Bryan
<item>John</item>
<
item>Matt开发者_如何学Python
<item>Mike</item>
<
/string-array>
I am confused as to how I can do a simple if statement that in pseudo-code looks like:
if (username_entered_in_editText == usernameArray[contents]) { submit_check = true; }
Any advice would be greatly appreciated!
Try something like this. Get an instance of your String[], get the text from your EditText with getText().toString(), and compare is to every name in the list. This isn't optimized, of course. If your String array is sorted, you could implement a binary search to make it faster, but the general theory here will work.
String[] usernames = getStringArray(R.array.usernames);
EditText editText = (EditText)findViewById(R.id.edittext);
String candidate = editText.getText().toString();
boolean submit_check = usernameTaken(candidate, usernames);
public boolean usernameTaken(String candidate, String[] usernames) {
for(String username : usernames) {
if(candidate.equals(username)) {
return true;
}
}
return false;
}
精彩评论