I have an EditText to give user comments.Now I want to input limit will be 500 words.
That means user can write comments maximum 500 words.
How can i implement this? Please help me.
You could use a TextWatcher to watch the text and not allow it to go beyond 500 words.
Implement your TextWatcher:
final int MAX_WORDS = 500;
final EditText editBox = (EditText) findViewById(<your EditText field>);
editBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Nothing
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String[] words = s.toString().split(" "); // Get all words
if (words.length > MAX_WORDS) {
// Trim words to length MAX_WORDS
// Join words into a String
editBox.setText(wordString);
}
}
});
Note: You may want to use something from this thread to join the String[] into wordString.
However, this is not the most efficient method in the world, to be frankly honest. In fact, creating an array of the entire String on each key entry may be very taxing, particularly on older devices.
What I would personally recommend is that you allow the user to type whatever they want, then verify it for word count when they hit submit. If it's <=500 words, allow it, otherwise deny it, and give them some kind of message (a Toast?) that tells them.
Lastly, verifying by word count is very iffy. Remember that there are things like (character 160) that can be used as spaces but would not be picked up by this. You are far better to pick a set character limit and restrict the field using the maxLength answers already provided.
I've tried writing this in XML file but it does not works:
This one works for sure and is actually a better solution to problem and you can also use it for custom validation rules:
InputFilter maxChars = new InputFilter.LengthFilter(500); // 500 Characters
editText.setFilters(new InputFilter[] { maxChars });
Related
create tag comment system in android same as facebook.
In comment section if we insert # and type then show list of friend. and choose one friend. I want this type of comment system same as facebook.
You can set a TextWatcher which will get triggered whenever text changes in your EditText. Then, you can use a Regex after an # is found to see if there is any #name followed by a space. If there is, you can make another UI element pop up which shows a ListView of friends which match the particular Regex. Here is an example which I came up with:
// Declare listening as a member variable
commentInput.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Listen until space
String text = charSequence.toString();
if (text.contains("#")) {
listening = true;
int index = text.split("#").length;
String textToSearchFor = text.split("#")[index];
// Use textToSearchFor to search for friends,
// and if you get results then set a UI element
// to appear: listView.setVisibility(View.VISIBLE);
// on click of ListView element, stop listening
} else if (text.substring(0, text.length() - 1).equals(" ")) {
// If the latest character is a space, then stop listening
listening = false;
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
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");
}
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.
}
I was wondering what is the best way to validate form ?
I did try the following:
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
if(fname_text.equalsIgnoreCase(""))
{
fname.setError("Field is required");
}
and also:
fname.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after){
}
#Override
public void afterTextChanged(Editable s)
{
Pattern mPattern = Pattern.compile("[A-Za-z]{2,20}$");
Matcher matcher = mPattern.matcher(s.toString());
if(!matcher.matches()) // on Success
{
fname.setError("Please make sure you input a valid first name");
}
}
});
The thing that I am confused in is that ... whenever the page loads for the first time, the error message is shown, but when I go inside the EditText and type some content, and if I erase the content, the error message does not persist. So how do I keep this validation persistent ??? Because the way that the program is shaping up, it looks like it won't validate anything very nicely. And you guys know some good links for regex in android with complete example, please do recommend.
And also, how will me putting the Pattern and Matcher methods in onTextChanged or beforeTextChanged affect the output ?
Instead of running the check right after
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
Use an OnFocusChangeListener and run it whenever the onFocusChange() method is called. Ideally, you'd run it only when the View loses focus. Something like:
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
fname.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if(!(v.isFocused())) {
//Run your validation
}
}
});
This way, you only run the Validation when the user is done typing, instead of everytime the user changes something.
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.