How do I get first three characters from an edittext?
android, eclipse
Solution
To get text from an EditText, or a TextView, Button, etc. (pretty much any View that has text), you call getText(). This returns a CharSequence, which is almost a String, but not quite, so to turn it into a String object, call toString() on it. And then to get the first 3 letters, use the substring() method, where the first argument is the index of the character to start, and the second is one past the last character you want. So you want the first 3 characters, which are indices 0,1,2, so we must have 3.
EditText yourEditText = (EditText) findViewById(R.id.your_edit_text);
CharSequence foo = yourEditText.getText();
String bar = foo.toString();
String desiredString = bar.substring(0,3);
In addition, you will probably want to make sure that the user has actually put something in the EditText before assuming that there is and getting a NullPointerException when you try to use the string. So i usually use EditTexts in the following way.
EditText yourEditText = (EditText) findViewById(R.id.your_edit_text);
String foo = yourEditText.getText().toString();
if(foo.length() > 0) { //just checks that there is something. You may want to check that length is greater than or equal to 3
String bar = foo.substring(0, 3);
//do what you need with it
}
Problem
I want to get the first three characters from an edittext and then turn them onto a string, but I cant find anything about that. Any ideas?