put a character on edittext while typing - android

I have an EditText, and I want to use it for input date, I want to make it so when user insert date, my app will automatically add '-' on EditText, so user only need to insert number,
ex;
user type: 21 -> device automatically 21-
user type: 01 -> device automatically 21-01-
user type: 2013 -> device automatically 21-01-2013
I tried this;
edtTxt1.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Integer textlength1 = edtTxt1.getText().length();
if (textlength1 == 2) {
edtTxt1.getText().insert(2, "-");
edtTxt1.setSelection(3);
/*I also tried this, no luck
edtTxt1.setSelection(edtTxt1.getText().length());*/
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
});
result:
user type: 21 -> device automatically 21-
user type: 01 -> device automatically 2101-
I can't put cursor after '-'
EDIT
I tried #svenoaks answer, I was able to put cursor after '-' but this is what happen:
user type: 21 -> device automatically 21-
user type: 0 -> device automatically 21-210

edtTxt1.setText(edtTxt1.getText().insert(2, "-"));

Did you know: you can always use DatePicker for getting date input from user.
Assuming you want to print dd-mm-yyyy, try this
if(textlength1==2||textlength1==5||textlength1==7)
edtTxt1.setText(edtTxt1.getText().insert(textlength1, "-"));

I think you could try edtTxt1.setText("....")

Related

Android TextWatcher behavior

Although code is far from being complete, for the begining I tried to detect via TextWatcher
when character is pressed in EditText that doesn't belong to hex values and not to permit it
to be displayed, but to inform user of error entry.
The excerpt from code follows, where arrayOfChars consists of 16 permitted hex chars and edt2
is EditText var. What I tried is to enter following chars: "aeyd", so it is aim to inform of
"y" as an error and not to display it.
edt2.addTextChangedListener(new TextWatcher(){
private boolean errorDetected= false;
private int oldbefore;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String st;
if (errorDetected){ //set in code bellow
errorDetected= false;
return;
}
st= s.toString();
if (before > 0){
if (before<= s.length()){st= s.subSequence(before, s.length()).toString();}
}
boolean velid= true;
for (char c: st.toCharArray()){
if (new String(arrayOfChars).indexOf(Character.toUpperCase(c))==-1){
edt2.setError("Wrong char - " + c);
errorDetected= true;
oldbefore= before;
velid= false;
break;
}
}
if (velid) {edt2.setError(null);}
}
#Override
public void afterTextChanged(Editable s) {
if (errorDetected){s.delete(oldbefore, s.length());}
}
});
When "y" is entered everything behave as expected- only "ae" displayed and error info also.
However when "d" is entered and breakpoint settled at the beginning of onTextChanged, I see
"s" parameter to be "aeyd"- so "y" is still preserved somehow.
Any help where I go wrong ?

User input shouldn't exceed a particular number entered in edittext in android

Am developing a hymn app in android, is there a way to let users know that the number they have entered cannot be found in the database, thus the hymn index they entered the hymn is not up to that number immediately the entered it in the edit text.
This is a section of the code
android:ems="10"
android:inputType="number"
android:maxLength="3"`
Restricting length of the EditText could work if your value is inside [-99;999].
Anyway you should read and then validate the number.
EditText.
a. If you have a button (user enters hymn number and clicks a button to find), then add something like this in your onClick method:
Editable e = yourEditText.getText();
String hymnNumberInString = "";
if (e != null) s = hymnNumberInString.toString();
if (hymnNumber.isEmpty()) showEmptyAlert(); //show alert that string is empty;
try {
Integer hymnNumber = Integer.valueOf(s);
if (!findHymn(hymnNumber)) {//here is a search
showErrorMessage();
}
} catch (NumberFormatException e) {
e.printStackTrace();
showErrorMessage();
}
b. If you do not have a button, you can add a TextWatcher and show error if hymn number is exceeded:
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s != null && s.length() != 0) {
try {
Integer hymnNumber = Integer.valueOf(s);
if (findHymn(hymnNumber)) {
//everything is ok, do what you want with it
// BUT!!! Remember that user might entered only 1 and is still entering!
// To ensure that user already entered (or maybe already entered) you can wait for 2 sec.
//E.g. by using someHandler.postDelayed(runnableWithThisCodeInside, 2000);
} else {
showErrorMessage();
}
} catch (NumberFormatException e) {
e.printStackTrace();
showErrorMessage();
}
}
}
});
c. You can use this nice library to simplify proccess of validation.
For predefined set of numbers you can use NumberPicker. This component takes a String array as input (via setDisplayedValues()) - so you can populate it with numbers/string from the database. And its editable (unless you restrict it) - so your user can still enter the number he wants.
is there a way to let users know that the number they have entered cannot be found in the database.
Yes you can do that,Considering you are using EditText to let user enter the number, get the text from there like below
EditText mEdit = (EditText)findViewById(R.id.edittext);
Integer number=Integer.valueOf(editText.getText.toString());
Now you have the number you can run a query on database table to match against the corresponding values, whether it exists in database or not.Something like this
int count= SELECT count(*) FROM tbl_user
WHERE name = ' + number + '
if(count>0){
Log.d("Count","Value exist in database");
}

Check blank space when clicking in a EditText

I have a customized EditText class, whats is happening is that there is a validation already for the field, checking it's length and doing trim.
But, the app is crashing because it is possible to click in the field and insert data after 1 space.
How can I validate when clicking, that user can not write his data? If he/she writes data with one space, the app crashes and I receive the following exception.
java.lang.IllegalArgumentException: Start position must be less than the actual text length
Thanks in advance.
Either you can trim but remember this wont restrict to enter white spaces by user, If you want to restrict white spaces then you need to add filter for your edit text. Adding filter let you restrict what ever character you want to avoid.
P.S - Check for adding filter on given link How do I use InputFilter to limit characters in an EditText in Android?
add "addTextChangedListener" to your EditText and then onTextChanged you can check for your validation. For example,
txtEdit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
String str = s.toString();
if(str.length() > 0 && str.startsWith(" ")){
Log.v("","Cannot begin with space");
txtEdit.setText("");
}else{
Log.v("","Doesn't contain space, good to go!");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Get the edit text first by this way:
EditText name=(EditText) findViewById(R.id.txt);
String txtEdit=txt.getEditableText().toString();
then check the text length validation by:
if(txtEdit.length() == 0) {
//your code for what you want to do.
}
trim the string that you get from edit text.
String str=edtext.getText().toString().trim();
if(str!=null && !str.equalsIgnoreCase("")))
{
//perform your operations.
}
else
{
//give error message.
}

First charector of EditText should be alphabet

In my EditText I want to enter the first character as alpha and the remaining is whatever. I achieved this task with the help of TextWatcher. But now my problem is if I entered something wrong(like digits, special characters) as my First character then my EditText shouldn't accept the remaining characters. If I correct my first character then only my EditText should accept. Is their any possibility to achieve this friends? If yes then please guide me friends.
My textWatcher code is
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (s.length() > 0) {
String str = edittext.getText().toString();
char t = str.charAt(0);
if (!Character.isLetter(t)) {
Toast.makeText(getApplicationContext(),
"please enter your first charecter as alpha",
Toast.LENGTH_LONG).show();
}
}
}
});
Thanks in advance.
CREATE UNIQUE INDEX ON UnnamedTable (Department) WHERE Designation='Head'
It's called a Filtered Index. If you're on a pre-2008 version of SQL Server, you can implement a poor-mans equivalent of a filtered index using an indexed view:
CREATE VIEW UnnamedView
WITH SCHEMABINDING
AS
SELECT Department From UnnamedSchema.UnnamedTable WHERE Designation='Head'
GO
CREATE UNIQUE INDEX ON UnnamedView (Department)
Execute the following query to view duplicates:
Select Department,Designation,count(*)
From [mytable] Group by Department,Designation
Now replace mytable with the table name and department and designation with the columns in the table. After execution the result set will show a count of more than one for duplicate records.

EditText in Google Android

I want to create the EditText which allow Numeric Values, Comma and Delete and other values are ignore.
So How I can achieve this by programming code ?
Thanks.
I achieved same thing using follwing code, hope you will also find help from it.
editText.addTextChangedListener(controller);
#Override
public void afterTextChanged(Editable s) {
if(s.trim.length() > 0)
{
int start = s.toString().length() - 1;
int a = (int) s.charAt(start);
if (!(a >= 48 && a <= 57 || a == 44))
s = s.delete(start, start + 1);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
To restrict what characters can be typed into an android EditText, you must set them in the android:digits XML attribute. See http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits . Make sure to also validate user input before putting it into storage.
just simple ,
you want to create a text-field like that you can enter the new string must have some grammar that you want to allow.
i have some email validation grammar that can help you.
string = "/alphabetics/number/special-character" ;
and another is
user-entered-string = " ";
just compare user-entered-string's lexems and you defined grammar.

Categories

Resources