Check textfield is empty in Android Studio - android

I am trying to check whether my textfield is empty for validation purpose but i am getting an error message cannot resolve method isEmpty
This is my partial coding:
private void addMovie(){
DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
if(getIntent().getExtras()== null){
databaseHandler.insertRow(
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
if (mvidEditText.isEmpty() || mvtitleEditText.matc) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
}else {
databaseHandler.updateRow(rowID,
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
}
}
Are there any ways to do this? I did some research from stack overflow too.Thank you.

Now in new version getText() is not working directly so use only text
like this
if (enter_name.text.toString().isEmpty()) {
}

As far as my knowledge goes, there is no method isEmpty() in EditText class. you should do like this-
if(!TextUtils.isEmpty(editTextRef.getText().toString())){
///.... your remaining code if the edittext is not empty
}

if(mvidEditText.getText().length() == 0){}

you can try following for checking empty value for edittext
mvidEditText.getText().toString().isEmpty();
where isEmpty returns true if length of this string is 0.

if(mvidEditText.getText().toString().equals("")){print message here}

to check Edittext is empty
if(myeditText.getText().toString().trim().length() == 0)
Or use below function
private boolean isEmpty(EditText editText) {
return editText.getText().toString().trim().length() == 0;
}

Related

Why does my radio buttons goes to "Please Try Again" after I clicked on the right answer

I have a problem. After I created a question, it suddenly goes to please try again rather than the answer is correct. Can you please explain what the problem is?
submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(questionchoice1.isChecked() || questionchoice2.isChecked() || questionchoice3.isChecked()) {
if (questionchoice1.equals(quizAnswer)) {
mAnswer.setText("The answer is correct!");
mAnswer.setVisibility(View.VISIBLE);
}
else if(questionchoice2.equals(quizAnswer))
{
mAnswer.setText("The answer is correct!");
mAnswer.setVisibility(View.VISIBLE);
}
else if(questionchoice3.equals(quizAnswer))
{
mAnswer.setText("The answer is correct!");
mAnswer.setVisibility(View.VISIBLE);
}
else if (!questionchoice1.equals(quizAnswer)){
mAnswer.setText("Please try again!");
mAnswer.setVisibility(View.VISIBLE);
}
else if (!questionchoice2.equals(quizAnswer)){
mAnswer.setText("Please try again!");
mAnswer.setVisibility(View.VISIBLE);
}
else if (!questionchoice3.equals(quizAnswer)){
mAnswer.setText("Please try again!");
mAnswer.setVisibility(View.VISIBLE);
}
}
else
{
mAnswer.setText("Please select an answer");
mAnswer.setVisibility(View.VISIBLE);
}
}
});
Your questionchoice is a radio button and your quizAnswer is a variable of a different type (String, int, ...? I'm guessing String if you're using .equals()). So the method is not comparing the value of the radio button, but its reference. Please post your layout and the variable types you're using and I can update my answer with further info on how to solve your problem.
UPDATE after comment:
Get the value of the radio button that’s checked using:
String quizChoice1 = questionchoice1.getText();
Then add the following to your check conditions:
if (quizChoice1.equals(quizAnswer)) {
//answer is correct
} else {
//answer is wrong
}
"questionchoice1" is a radio button so you have to get the text of the Radio button first then compare that text to value in your variable "quizAnswer".
in java we can get text of radio button as
String value = questionchoice1.getText();
and in kotlin:
val value = questionchoice1.Text
then we can compare tat value to variable as
value.equal(quizAnswer)

How to Check the empty text fields before uploading image or video in android?

I'm new to stackoverflow and android, sorry if i'm wrong. I am trying to check the text fields is empty or not, when the text field is empty, upload button should show please enter title and when user enters the text then only it should upload the image. After entering title then also it again shows the toast.
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title1.matches("")){
Toast.makeText(getApplicationContext(), "Please enter the Title and Category", Toast.LENGTH_SHORT).show();
} else if(description1.matches("")){
Toast.makeText(getApplicationContext(), "Please Select Category", Toast.LENGTH_SHORT).show();
} else {
flag = 1;
// uploading the file to server
new UploadFileToServer().execute();
}
}
});
Any help would be appreciated.
To check for empty fields, use
if(TextUtils.isEmpty(editText.getText().toString())) {
// do something
}
or if you want to check if string is empty or null use -
if(TextUtils.isEmpty(stringToCheck) {
// do something
}
try this.
Place this code in your button onClickListener:
String mText = mEditText.getText().toString();
if(TextUtils.isEmpty(mText)){
//Do what you want(Edittext is NULL)
}else{
//Do what you want(Not NULL)
}
Try to get value from your edittext like below:
Globally declare variable : -
String editvalue;
In onCreate() :-
EditText youredittext = (EditText)findViewById(R.id.youredittextid);
editvalue = youredittext.getText.toString().trim();
Now in your condition check :
if(editvalue.isEmpty() || editvalue == null){
// Do what you want when editText's value is null or empty
}else{
}
You can also use
TextUtils.isEmpty(CharSequence str)
for empty and null string check.
Returns true if the string is null or 0-length

AutoCompleteTextView allow only suggested options

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.

EditText setError message does not clear after input

Ok so I only have a EditText field and a button, which when pressed triggers an AsyncTask.
EditText playerName = (EditText)findViewById(R.id.playerEditText);
if(playerName.getText().toString().length() == 0 )
playerName.setError("Player name is required!");
else {
// do async task
}
The problem is that the error message seems to stay up even after when I input valid text to search. Is there a way to remove the error as soon as the EditText is not empty?
In your else bracket, put playerName.setError(null), which will clear the error.
API documentation: "The icon and error message will be reset to null when any key events cause changes to the TextView's text."
Though it is not so - and therefore we can regard this as bug.
If you use inputType such as textNoSuggestions, textEmailAddress, textPassword, the error is unset after a character is typed. Nearly as documented but again not exactly - when you delete a character, error stays.
It seems, a simple workaround with addTextChangedListener and setError(null) can attain promised behavior.
Besides there are posts about icon losing on Android 4.2. So use with care.
Try this listener:
playerName.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable edt){
if( playerName.getText().length()>0)
{
playerName.setError(null);
}
}
If you want to hide the error message one way is you apply onclicklistener on the edit box and then
editTextName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editTextName.setError(Null)
}
});
Below code worked for me
#OnTextChanged(
value = R.id.editTextName,
callback = OnTextChanged.Callback.TEXT_CHANGED)
public void afterInput(CharSequence sequence) {
editTextName.setError(null);
editTextName.setErrorEnabled(false);
}
'
editTextName.setError(null) Will clear the error message.
editTextName.setErrorEnabled(false) Will remove additional padding.
Add a TextWatcher to your EditText and onError, show your error message using et.setError(errorMessage) else you can remove the error message and error icon like below.
// to remove the error message in your EditText
et.setError(null);
// to remove the error icon from EditText.
et.setCompoundDrawables(null, null, null, null);
This code worked for me.
textInputSetting(binding.emailEdt)
fun textInputSetting(view: TextInputLayout) {
view.apply {
this.editText!!.addTextChangedListener {
if (this.editText!!.text.isNotEmpty()) {
this.error = null
this.isErrorEnabled = false
}
}
}
}

where to put checking edittext syntax?

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

Categories

Resources