Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get first three characters from an edittext? [closed]

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?

like image 220
user3686028 Avatar asked May 29 '14 03:05

user3686028


People also ask

How do you get the first two characters in a string with Kotlin?

To get character at specific index of String in Kotlin, use String. get() method. Given a string str1 , and if we would like to get the character at index index in the string str1 , call get() method on string str1 and pass the index index as argument to the method as shown below.

How do I show errors in EditText?

In order to show the error below the EditText use: TextInputLayout til = (TextInputLayout) findViewById(R. id. username); til.


1 Answers

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
}
like image 193
cjbrooks12 Avatar answered Nov 15 '22 05:11

cjbrooks12