Focus removed while typing in edit text - android

I have an EditText
serialText = (EditText) findViewById(R.id.pinText);
Now onclick of somebutton, I should get the focus to edit text to write something. But when I click inside of edit text to write, focus is getting removed, i.e., whatever i type does not appear in the edit text
This is the code to do that,
public void method(View v) {
arrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
serialNumber = serialText.getText().toString();
if (serialNumber.equals("")) {
} else {
}
} }...
Here if I don't type anything it comes to if loop without any problem, but samething is not happening for else part.
Can you please help me?
This is my full code
public void onClick(View v) {
if (v.getId() == R.id.pinBtn) {
arrowButton = (Button) findViewById(R.id.arrowBtn);
serialText = (EditText) findViewById(R.id.pinText);
serialText.setVisibility(View.VISIBLE);
arrowButton.setVisibility(View.VISIBLE);
//serialNumber = serialText.getText().toString();
arrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
serialNumber = serialText.getText().toString();
if (serialNumber.equals("")) {
Toast.makeText(getApplicationContext(),
"Please enter the serial number",
Toast.LENGTH_SHORT).show();
}
else {
isRegularSerialNumber(serialNumber);
String encodedserialNumber = Base64.encodeToString(
serialNumber.getBytes(), Base64.DEFAULT);
receiveSerialData(encodedserialNumber);
if (serialResponse.equals("Validated Successfully!")) {
showAudio(v);
} else {
Toast.makeText(getApplicationContext(),
"Invalid Serial Number", Toast.LENGTH_SHORT)
.show();
}
}
}
});
}
}
Thanks

I solved the problem finally, the problem was when we keep an edit text in the listview and when try to write inside that, keyboard pushes the listview up. So we need to add the property android:windowSoftInputMode="adjustPan" to the listview or to the activity containing the list view in the manifest file.

Instead of using serialNumber.equals(""), try replacing it with:
serialNumber.length() == 0
or
serialNumber.matches("")

The code you posted is onClick() of arrowButton, you should post onClick() of serialText

Related

How to delete edittext dynamically everytime I click a button

I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.
// Add On
addOnLayout.removeAllViews();
addFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddOnCounters++;
etFoodName = new EditText(addfoodAddOn.this);
etFoodName.setId(ETFoodID);
etFoodName.setHint("Enter your AddOn Name");
etPrice = new EditText(addfoodAddOn.this);
etPrice.setId(ETPriceID);
etPrice.setHint("Enter your AddOn Price");
Log.d("-------","-------------------what is edittext name id " + ETFoodID);
Log.d("-------","-------------------what is edittext price id " + ETPriceID);
ETFoodID++;
ETPriceID++;
addOnLayout.addView(etFoodName);
addOnLayout.addView(etPrice);
}
});
removeFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){
addOnLayout.removeViewAt(ETFoodID);
addOnLayout.removeViewAt(ETPriceID);
ETFoodID--;
ETPriceID--;
}
}
});
I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.
Replace your listener
removeFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){
View v1 = addOnLayout.findViewById(ETFoodID);
View v2 = addOnLayout.findViewById(ETPriceID);
addOnLayout.removeView(v1);
addOnLayout.removeView(v2);
ETFoodID--;
ETPriceID--;
}
}
});
After the button click just do this:
addFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etPrice.setText("")
etFoodName.setText("");
}
}
Remove it from its parent.
removeFields.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeFromParent(etFoodName);
removeFromParent(etPrice);
}
});
static void removeFromParent(View view) {
((ViewGroup)view.getParent()).removeView(view);
}

Android code for checking visibility of edit text

Hi i have a small problem. I have spinner when i select "yes" edit text 1 and edit text 2 will display when i select "NO" edit text will disappear its working fine for me. But when i press on button for validating the edit text logcat as "AUDIO_OUTPUT_FLAG_FAST denied by client". this is the code.
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(edittext1.getText().toString().length()==0)
{
Toast.makeText(getApplicationContext(), "Please Enter Key NO(FX)", Toast.LENGTH_SHORT).show();
}
else if(sfpchangeddata.contains("SFP Changed"))
{
Toast.makeText(getApplicationContext(), "Please Select SFP changed or Not", Toast.LENGTH_SHORT).show();
}
else if(edittext2.getVisibility()==View.VISIBLE)
{
if(edittext2.getText().toString().length()!=0)
{
}
else
{
Toast.makeText(getApplicationContext(), "Please Enter Siga SFP serial No", Toast.LENGTH_SHORT).show();
}
}
else if(edittext3.getVisibility()==View.VISIBLE)
{
if(edittext3.getText().toString().length()!=0)
{
}
else
{
Toast.makeText(getApplicationContext(), "Please Enter Old Siga SFP serial No", Toast.LENGTH_SHORT).show();
}
}
}
});
isShown() method returns boolean value, so you can use this in your if loop.
if(edittext.isShown())
{
//Set the code here if the edittext is visible.
}
else
{
//Here the code which will run if ediitext is invisible.
}
Hope this will help you.
You can check the visibility for an editText by using isShown() on your ediText

Android test if it having data else return to first

I have android apps:
Send data to Textview (working)
check if data is there getdata from text view(working)
Else if data not in Textview check again ??
Thanks.
button1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
//enter text to TextView (tv1) need some time
EntertextToTextView();
//label1
if (tv1.getText().toString() != "")
{
tv2.setText(tv1.getText().toString());
}
else {
// goto label1;
}
}
}
});

how to get text from radiobutton in string and check whether it is empty or not

What is the error in radioButton1.getText().toString().equals("") in code below?
I want to force the user to fill in this field and if he leaves the field empty then toast a message that fills the required field. How do I do this?
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(radioButton1.getText().toString().equals("")||radioButton2.getText().toString().equals("")||radioButton3.getText().toString().equals("")||radioButton4.getText().toString().equals("")
||petn.getText().toString().equals("")||breed.getText().toString().equals("")||color.getText().toString().equals("")||alergic.getText().toString().equals("")||ath_locat.getText().toString().equals("")||d_condi.getText().toString().equals("")||weight1.getText().toString().equals("")
)
{
Log.e("onclick", ",pd");
Toast msg = Toast.makeText(
My2Activity.this,"Please fill the * required field",Toast.LENGTH_LONG);
msg.show();
}
else{
PostData();
Intent d = new Intent(getApplicationContext(),
My1Activity.class);
startActivity(d);
}
}
});
if(radioButton1.isChecked())
{
}
else
{
}
you want to set OnCheckedChangeListener to radio button
radioButton1.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
}
}
I think you should use
radioButton1.isChecked()

How do I check if my EditText fields are empty? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have 5 EditTexts in android. I would like to know if I could check if all 5 EditTexts are null. Is there any way to do this??
I did something like this once;
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
OR As Per audrius
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() == 0;
}
If function return false means edittext is not empty and return true means edittext is empty...
For validating EditText use EditText#setError method for show error and for checking empty or null value use inbuilt android class TextUtils.isEmpty(strVar) which return true if strVar is null or zero length
EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
etUserName.setError("Your message");
return;
}
try this :
EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
or use the TextUtils class like this :
if(TextUtils.isEmpty(strUserName)) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Way late to the party here, but I just have to add Android's own TextUtils.isEmpty(CharSequence str)
Returns true if the string is null or 0-length
So if you put your five EditTexts in a list, the full code would be:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText was empty
// Do something fancy
}
}
Other answers are correct but do it in a short way like
if(editText.getText().toString().isEmpty()) {
// editText is empty
} else {
// editText is not empty
}
Try this
TextUtils.isEmpty(editText.getText());
You can use length() from EditText.
public boolean isEditTextEmpty(EditText mInput){
return mInput.length() == 0;
}
I usually do what SBJ proposes, but the other way around. I simply find it easier to understand my code by checking for positive results instead of double negatives.
You might be asking for how to check for empty EdiTexts, but what you really want to know is if it has any content and not that it is not empty.
Like so:
private boolean hasContent(EditText et) {
// Always assume false until proven otherwise
boolean bHasContent = false;
if (et.getText().toString().trim().length() > 0) {
// Got content
bHasContent = true;
}
return bHasContent;
}
As SBJ I prefer to return "has no content" (or false) as default to avoid exceptions because I borked my content-check. That way you will be absolutely certain that a true has been "approved" by your checks.
I also think the if calling it looks a bit cleaner as well:
if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}
It is very much dependent on preference, but i find this easier to read. :)
Why not just disable the button if EditText is empty? IMHO This looks more professional:
final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
txtFrecuencia.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
toggle.setEnabled(txtFrecuencia.length() > 0);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
I use this method, that uses trim() to avoid blank spaces :
EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
return;
}
an example if you have several EditText´s
if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(textA.getText())){
showToast(it's Null");
}
you can use TextUtils.isEmpty like my Example !
Good luck
with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string
EditText user = findViewById(R.id.user);
userString = user.getText().toString().trim();
if (userString.matches("")) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
return;
}else{
Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}
private boolean hasContent(EditText et) {
return (et.getText().toString().trim().length() > 0);
}
I used TextUtils for this:
if (TextUtils.isEmpty(UsernameInfo.getText())) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
You can also check all the EditText Strings in one If condition: like this
if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
}
I wanted to do something similar. But getting the text value from edit text and comparing it like (str=="") wasn't working for me. So better option was:
EditText eText = (EditText) findViewById(R.id.etext);
if (etext.getText().length() == 0)
{//do what you want }
Worked like a charm.
Try this out with using If ELSE If conditions. You can validate your editText fields easily.
if(TextUtils.isEmpty(username)) {
userNameView.setError("User Name Is Essential");
return;
} else if(TextUtils.isEmpty(phone)) {
phoneView.setError("Please Enter Your Phone Number");
return;
}
You could call this function for each of the edit texts:
public boolean isEmpty(EditText editText) {
boolean isEmptyResult = false;
if (editText.getText().length() == 0) {
isEmptyResult = true;
}
return isEmptyResult;
}
EditText txtUserID = (EditText) findViewById(R.id.txtUserID);
String UserID = txtUserID.getText().toString();
if (UserID.equals(""))
{
Log.d("value","null");
}
You will see the message in LogCat....
"check out this i m sure you will like it."
log_in.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=user_name.getText().toString();
password=pass_word.getText().toString();
if(username.equals(""))
{
user_name.setError("Enter username");
}
else if(password.equals(""))
{
pass_word.setError("Enter your password");
}
else
{
Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
startActivity(intent);
}
}
});
use TextUtils.isEmpty("Text here"); for single line code
The following works for me all in one statement:
if(searchText.getText().toString().equals(""))
Log.d("MY_LOG", "Empty");
First I retrieve a text from the EditText and then convert it to a string and finally comparing it with "" using .equals method.
This function work for me
private void checkForm() {
EditText[] allFields = {
field1_txt,
field2_txt,
field3_txt,
field4_txt
};
List < EditText > ErrorFields = new ArrayList < EditText > ();
for (EditText edit: allFields) {
if (TextUtils.isEmpty(edit.getText())) {
// EditText was empty
ErrorFields.add(edit); //add empty Edittext only in this ArayList
for (int i = 0; i < ErrorFields.size(); i++) {
EditText currentField = ErrorFields.get(i);
currentField.setError("this field required");
currentField.requestFocus();
}
}
}
}
EditText edt=(EditText)findViewById(R.id.Edt);
String data=edt.getText().toString();
if(data=="" || data==null){
Log.e("edit text is null?","yes");
}
else {
Log.e("edit text is null?","no");
}
do like this for all five edit text
You can use setOnFocusChangeListener , it will check when focus change
txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if (arg1) {
//do something
} else {
if (txt_membername.getText().toString().length() == 0) {
txt_membername
.setError("Member name is not empty, Plz!");
}
}
}
});
if ( (usernameEditText.getText()+"").equals("") ) {
// Really just another way
}
I prefer using ButterKnife list binding and then applying actions on the list. For example, with the case of EditTexts, I have the following custom actions defined in a utility class (in this case ButterKnifeActions)
public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = true;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
}
return hasProperty;
}
public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = false;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
}
return hasProperty;
}
public interface Check<V extends View> {
boolean checkViewProperty(V view, int index);
}
public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
#Override
public boolean checkViewProperty(EditText view, int index) {
return TextUtils.isEmpty(view.getText());
}
};
And in the view code, I bind the EditTexts to a list and apply the actions when I need to check the views.
#Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
And of course this pattern is extendable to checking any property on any number of views. The only downside, if you can call it that, is the redundancy of views. Meaning, to use those EditTexts, you would have to bind them to single variables as well so that you can reference them by name or you would have to reference them by position in the list (edits.get(0), etc.). Personally, I just bind each of them twice, once to a single variable and once to a the list and use whichever is appropriate.
To editText is empty try another this simple way :
String star = editText.getText().toString();
if (star.equalsIgnoreCase("")) {
Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}
Try this out:
its in Kotlin
//button from xml
button.setOnClickListener{
val new=addText.text.toString()//addText is an EditText
if(new=isNotEmpty())
{
//do something
}
else{
new.setError("Enter some msg")
//or
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
Thank you

Categories

Resources