I have a DialogFragment that contains AutoCompleteTextView, and Cancel and OK buttons.
The AutoCompleteTextView is giving suggestions of usernames that I'm getting from server.
What I want to do is to restrict the user to be able to enter only existing usernames.
I know I can do check if that username exists when the user clicks OK, but is there some other way, let's say not allow the user to enter character if there doesn't exist such username. I don't know how to do this because on each entered character I'm getting only up to 5 suggestions. The server is implemented that way.
Any suggestions are welcomed.
Thank you
I couldn't find more suitable solution then this:
I added this focus change listener
actName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ArrayList<String> results =
((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
if (results.size() == 0 ||
results.indexOf(actName.getText().toString()) == -1) {
actName.setError("Invalid username.");
};
}
}
});
Where the method getAllItems() returns the ArrayList containing the suggestions.
So when I enter some username, and then move to another field this listener is triggered and it checks if the suggestions list is not empty and if the entered username is in that list. If the condition is not satisfied, an error is shown.
Also I have the same check on OK button click:
private boolean checkErrors() {
ArrayList<String> usernameResults =
((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
if (actName.getText().toString().isEmpty()) {
actName.setError("Please enter a username.");
return true;
} else if (usernameResults.size() == 0 || usernameResults.indexOf(actName.getText().toString()) == -1) {
actName.setError("Invalid username.");
return true;
}
return false;
}
So if the AutoComplete view is still focused, the error check is done again.
Related
this is the question Shows the log-in form; the app must generate a message box notifying the user “Please Complete the required field” when the user leave the two text boxes blank ,while clicking the login button; wherein a generated message box pop and notify the user that “Wrong password!” when the user input the correct username and wrong password it will automatically clear the password textbox; wherein the app must generate a message box that notify the user that “Wrong Username!” if the user input the wrong username and correct password it will and automatically clear the username textbox; wherein the app must generate a messages box that notify the user that “Wrong Username and password!” if the user input both wrong username and wrong password it will automatically clear the password and username textboxes and set the text focus to the username textbox; wherein ;the app must notify the user “WELCOME” if when the user input the correct username and password it will automatically close the login activity and open the next activity.
Note: the Username and password must be both “admin”.
Button login;
EditText user, pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText)findViewById(R.id.editText1 );
pass = (EditText)findViewById(R.id.editText2 );
login = (Button)findViewById(R.id.button1 );
login.setOnClickListener((OnClickListener) this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(user.equals("admin") && (pass.equals("admin"))){
System.out.println("Welcome!");
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}else if (user.equals(null) && (pass.equals("admin"))) {
System.out.println ("Please Complete Required Field!");
}else if (user.equals("admin") && (pass.equals(null))) {
System.out.println ("Please Complete Required Field!");
}else {
System.out.println ("Wrong Username! or Wrong Password!");
}
}
}
To detect whether the editText is empty or not:
Change (user.equals(null)) to user.getText().toString().trim().length() == 0
and pass.equals(null) to pass.getText().toString().trim().length() == 0
In your button implementation, write like login.setOnClickListener(this); and make sure your Activity/Fragment implement OnClickListener like #pcg26 said.
Make sure you have implemented onClickListener.
In your onClick method, You must use a switch or if statement to make sure that the button is clicked.
Something like this:
public void onClick(View v) {
if(v.getId() == R.id.yourButtonID){
// do here
}
}
Is the activity implementing onclicklistener?
Simple a comment.. You can use Log.e("MyActivity"," the error"); instead System.out.println ^^
I have done a database for the suggestion words
but where to put it into the android soft keyboard example and how to use the words from db in the program? so that I will not need to type the word completely and it will shown the suggestion word in database
Inside the SDK check out the Samples folder, this contains a soft keyboard example and more information on how to suggest results.
You just need to handle database in SoftKeyboard.java Class.
To get the suggestion words from .db, please use SQLiteOpenHelper or SQLiteAssetsHelper.
To show the suggestion words in candidate view, please modify the updateCandidates() method of SoftKeyboard.java file in Google SoftKeyboard example project.
/**
* Update the list of available candidates from the current composing
* text. This will need to be filled in by however you are determining
* candidates.
*/
private void updateCandidates() {
if (!mCompletionOn) {
// mComposing is current text you typed.
if (mComposing.length() > 0) {
// Get suggested words list from your database here.
ArrayList<String> list = new ArrayList<String>();
list.add(mComposing.toString());
// This method will show the list as suggestion.
setSuggestions(list, true, true);
} else {
setSuggestions(null, false, false);
}
}
}
To enter the picked word from candidate view to input text, please modify following method in SoftKeyboard example project.
public void pickSuggestionManually(int index) {
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
getCurrentInputConnection().commitCompletion(ci);
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (mComposing.length() > 0) {
// If we were generating candidate suggestions for the current
// text, we would commit one of them here. But for this sample,
// we will just commit the current text.
commitTyped(getCurrentInputConnection());
// You need to add getter method for suggested words shown in candidate view
}
}
i need a favor.. i'm confused to put these codes to check whether the edittext is empty or not:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
where must i write these codes? is it between these codes?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuawal);
...
...
...
JmlAhliWarisAnakLK = (EditText) findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
or in this function after double sisa=0;??
public void cc() {
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
int JmlWarisAnakLK = Integer.parseInt(JmlAhliWarisAnakLK.getText().toString());
int JmlHarta = Integer.parseInt(JmlHartaPeninggalan.getText().toString());
double HasilSuami = 0;
double HasilIstri = 0;
double HasilAnakLK = 0;
double HasilAnakPR = 0;
double sisa = 0;
}
please correct me if i'm wrong.. :D
you are on the right track
After you set the layout using setContentView you need to add your EditText's which you are doing fine as follows.
JmlAhliWarisAnakLK = (EditText)findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
You then need to store the value you get from the EditText's in some variable,
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
....
....
After you have stored your values you can then call some method that validates your input on click of a button(if you have):
public void validateinput()
{
if(input == null || input.trim().equals(""))
{
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
}
According to me, you should put the check on some event, like if its login screen, then on click of submit button. or other wise on focus change it main instantly provide user with the toast that he left the field empty. or if other case, please provide more information for your query. thanks.
That depends on when you want to validate the editText..You propably have some button which "submits" the EditText so call this code in after onClick event gets fired on the button..
Put the input validation code when you have to navigate away from the current activity, either to go to another activity or to save the input details. That's the least annoying place to shove an error message onto the user.
Another approach is to validate when the focus leaves the EditText. But in this case the error notification should be more subtle (and therefore less annoying) like changing the EditText's background to lightred.
Ur questions does not seem to be clear. Are u asking where do u need to put the validation for empty edittext? If this is ur question then the general case would be to validate during any events such as BUTTON CLICK. Set the onClickListener for ur button and inside ur onclick perform the validation.
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
Your above code is pretty much correct. You Must need to add above code whenever you want to take input from these edittext, Or whenever you want to save these value. make a function which will return true if edit text is empty so u can ask user to enter values
public boolean isETEmpty(){
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
return true;
}
return false; // if not empty
}
call this function Whenever u want to use values from ET, if this function return true, you must let user enter values. Such as on Button Click to save etc
I have an activity that has two EditText boxes, one email and one plain text. I want to check that the email box is not empty and also that is matches an email pattern before allowing the user to move on. The pattern matcher part works, but the empty string part doesn't.
I validate as the user enters data, and then set the two buttons to the be clickable or not according to whether the email is correct. However, if the box is empty, it allows the user to press the button when it shouldn't. When there is text in the box, it does the correct thing of only letting the user press the button when the email pattern has been matched.
My after text changed method:
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String enteredEmail = email.getText().toString();
if (validateEmail(enteredEmail) == true) {
image1.setImageResource(R.drawable.greentick);
play.setClickable(true);
play.setFocusable(true);
existingUser.setClickable(true);
existingUser.setFocusable(true);
}
else {
System.out.println("Invalid");
image1.setImageResource(R.drawable.redcross);
play.setClickable(false);
play.setFocusable(false);
existingUser.setClickable(false);
existingUser.setFocusable(false);
}
}
And my validateEmail() method:
public boolean validateEmail(String email) {
boolean validated = false;
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() && (! email.equals("")) ) {
validated = true;
}
else {
validated = false;
}
return validated;
}
TextChanged won't fire if the user hasn't entered anything, as the text hasn't changed... You should disable the button by default.
Have you tried debugging, as this should have shown you the event isn't firing.
this is how i validate email fields (regular expressions):
private Boolean validateEmail(String email)
{
return email.matches("^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*#[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
}
FYI: i dont remember offhand, you may need org.apache.commons.lang3.stringutils
I have created an activity that refresh quotes when the user clicks a button. Within the same activity there is a check box which the users can click if they like the quote.
Everything works perfectly apart from the check box. When the user clicks they like the quote, I want that check box checked. This only happens when the user moves away from the activity and returns at a later stage.
However when the user stays within the activity and returns to the quote, the old state is shown instead of the users preference.
The check box is configured from the values even in the database, if the value is 1, the check box should be ticked, if not, check box should be clear.
The code is shown below:
When the user clicks the next button, the following code is executed:
Button nextGenerateButton = (Button) findViewById(R.id.btn_next_quotes);
nextGenerateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nextQuote = myDbHelper.getnextQuote();
setQuoteDisplay(nextQuote);
btn_favorite.setChecked(myDbHelper.getFavouriteCheckBoxValue());
}
});
The button retrieves the next quote and the getFavouriteCheckBoxValue() confirms whether the favourite column is marked in the database and either returns a true of false which sets the check box value.
public boolean getFavouriteCheckBoxValue()
{
int laballedFavourite = cursor.getInt(0);
if(laballedFavourite == 0)
{
return false;
}
else
{
return true;
}
}
if the user likes the quote, the code executes the addFavourite() which updates the table where the favourite column will be modified on one.
btn_favorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked == true)
{
myDbHelper.addFavourite();
}
if(isChecked == false)
{
myDbHelper.removeFavourite();
}
}
});
public void addFavourite()
{
ContentValues vals = new ContentValues();
vals.put("favouriteQuote", 1);
db.update(TABLE_NAME, vals, "columnId = " + cursor.getInt(1), null);
}
Again this only works perfectly when I resume the quote activity and not when I am currently live in the quote activity.
Hope this makes sense.
Any help would be greatly appreciated.
You need to refresh your checkbox to see the changement because you made a changement in you db but not on the UI. You need to observe the db and refresh the checkbox after a modification.
Refreshing cursor solved the problem.