Checking for empty edittext android - android

I have an edittext with input type set to number. I want to check if edittext is empty.
<EditText
android:id="#+id/noOfTranset"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Enter number:"
android:inputType="number"
android:textColor="#android:color/black"
android:maxLength="2"/>
Below is the code which I have tried but doesn't checks for empty edittext. What am I missing here? Thanks.
String numTrans = et1.getText().toString();
int transaction = Integer.parseInt(numTrans);
if(numTrans.trim().length() == 0 || numTrans.equals("") || numTrans == null){
// none of the above conditions check for empty edittext
}

Problem is your trying to convert the empty string to an Integer. Integer.parseInt will throw NumberFormatException when the input text is null or empty.
Change your code to parse string to integer only when the input text is not empty
if(!TextUtils.isEmpty(numTrans)){
int transaction = Integer.parseInt(numTrans);
// do your other stuff here
}

How about something like this?
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;
}
Taken from: Check if EditText is empty.

This is very simple you should check by using trim function like:
String numTrans = et1.getText().toString();
if(!numTrans.trim().length() > 0)
{
int transaction = Integer.parseInt(numTrans);
//code here for empty edittext....
}

Related

Get the String value of the EditText which has inputType numberPassword

I would like to get the String value of an EditText that has the attribute inputType: numberPassword, how do I do it?
Code_pin.getText().ToString() always returns a null value.
String str = null;
str = your_edit.getText().toString().trim(); //put your editText value in string
if (!TextUtils.isEmpty(str)) //check for empty
{
// Do your task here
}
First you have to get an Id of the EditText:
EditText et_pwd = (EditText) findViewById(R.id.et_pwd);
your xml file:
<EditText
android:id="#+id/et_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberPassword" />
then you call getText() method:
String text = et_pwd.getText().toString().trim();
if (text.equalsIgnoreCase("")) {
// empty/blank string
}else {
// not blank string
}

android: Log in Button

I'm having problem with my Log in activity.. the button will load the next activity even though no data inputted on the text field..
here's the code...
public void onButtonClick(View v){
if(v.getId()== R.id.Blogin) {
EditText a = (EditText)findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(User.this, Userlog.class);
i.putExtra("Username",str);
startActivity(i);
}
else
{
Toast temp = Toast.makeText(User.this, "Username and Password don't match!", Toast.LENGTH_SHORT);
temp.show();
}
Check for empty strings
replace
if(pass.equals(password))
with
if(pass.equals(password) && !TextUtils.isEmpty(str) && !TextUtils.isEmpty(pass))
This should work.
Cheers
You can check if a String is empty using the TextUtils class's isEmpty method, which is a static one.
// Checks if a username & a password were typed, then checks if password is correct
if(!TextUtils.isEmpty(str) && !TextUtils.isEmpty(pass) && pass.equals(password))
Notice that you are not checking whether the username is valid or not.
In you helper. searchPass(), do you return an empty string if no usrName is matched?If so, you have to check if the returned string is empty or you can return another special value :D

Android: Check if EditText is Empty when inputType is set on Number/Phone

I have an EditText in android for users to input their AGE. It is set an inputType=phone.
I would like to know if there is a way to check if this EditText is null.
I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.
These, I've checked already and do not work:
(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.
Thank you for your help.
You can check using the TextUtils class like
TextUtils.isEmpty(ed_text);
or you can check like this:
EditText ed = (EditText) findViewById(R.id.age);
String ed_text = ed.getText().toString().trim();
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
//EditText is empty
}
else
{
//EditText is not empty
}
First Method
Use TextUtil library
if(TextUtils.isEmpty(editText.getText().toString())
{
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Second Method
private boolean isEmpty(EditText etText)
{
return etText.getText().toString().trim().length() == 0;
}
Add Kotlin getter functions
val EditText.empty get() = text.isEmpty() // it == ""
// and/or
val EditText.blank get() = text.isBlank() // it.trim() == ""
With these, you can just use if (edittext.empty) ... or if (edittext.blank) ...
If you don't want to extend this functionality, the original Kotlin is:
edittext.text.isBlank()
// or
edittext.text.isEmpty()
EditText textAge;
textAge = (EditText)findViewByID(R.id.age);
if (TextUtils.isEmpty(textAge))
{
Toast.makeText(this, "Age Edit text is Empty", Toast.LENGTH_SHORT).show();
//or type here the code you want
}
I use this method for same works:
public boolean checkIsNull(EditText... editTexts){
for (EditText editText: editTexts){
if(editText.getText().length() == 0){
return true;
}
}
return false;
}
Simply do the following
String s = (EditText) findViewByID(R.id.age)).getText().toString();
TextUtils.isEmpty(s);
I found that these tests fail if a user enters a space so I test for a missing hint for empty value
EditText username = (EditText) findViewById(R.id.editTextUserName);
EditText password = (EditText) findViewById(R.id.editTextPassword);
// these hint strings reflect the hints attached to the resources
if (username.getHint().equals("Enter your username") || password.getHint().equals("Enter Your Password")){
// enter your code here
} else {
// alls well
}
editText.length() usually works for me
try this one
if((EditText) findViewByID(R.id.age)).length()==0){
//do whatever when the field is null`
}
Java: Check if EditText is Empty
1) find the EditText
ourEditText = view.findViewById(R.id.edit_text);
2) Get String value of EditText
String ourEditTextString = ourEditText.getText().toString();
3) Remove all spaces
Incase user inputs only blank spaces.
String ourEditTextNoSpaces = ourEditTextString.replaceAll(" ","");
3) Check if empty
boolean isOurEditTextEmpty = ourEditTextNoSpaces.isEmpty();
Try this. This is the only solution I got
String phone;
try{
phone=(EditText) findViewByID(R.id.age)).getText().toString();
}
catch(NumberFormatException e){
Toast.makeText(MainActivity.this, "plz enterphone Number ", Toast.LENGTH_SHORT).show();
return;
}

Android: Button enabled property is not working

i have the String in Edit Text, i want to change change the button state through the string. Please help me out of this problem i am beginner in android.
Here is the code.
String Result = jsonResult.toString();
JSONObject jsonResponse = new JSONObject(Result);
int successValue = jsonResponse.getInt("success");
String messageValue= jsonResponse.getString("message");
String successStringValue = String.valueOf(successValue);
String messageStringValue = String.valueOf(messageValue);
t1.setText(messageStringValue);
String tt1=t1.getText().toString();
if (tt1 != "Appointment is ready."){
b1.setEnabled(true);}
else{
b1.setEnabled(false);}
Change your condition to
if (tt1.equalsIgnoreCase("Appointment is ready.")){
b1.setEnabled(true);
}
else
{
b1.setEnabled(false);
}
use this code for making edittext not editable
<EditText ...
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false">
</EditText>
if(!(tt1.equals("Some String")))
{
//enable button
}
else
{
//disable it
}
Stings are compared by doing ".equals()"

Converting EditText to int? (Android)

I am wondering how to convert an EditText input to an int, I have the user input a number, which then divides it by 8.
MainActivity.java:
#SuppressWarnings("unused")
public void calcSpeed(View view)
{
setContentView(R.layout.activity_speed);
final TextView mTextView = (TextView) findViewById(R.id.textView3);
mTextView.setText("You should be getting: " +netSpedCalcd);
}
activity_main.xml:
<EditText
android:id="#+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="62dp"
android:ems="10" >
you have to used.
String value= et.getText().toString();
int finalValue=Integer.parseInt(value);
if you have only allow enter number then set EditText property.
android:inputType="number"
if this is helpful then accept otherwise put your comment.
Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.
I'm very sleepy and tired right now but wouldn't this work?:
EditText et = (EditText)findViewById(R.id.editText1);
String sTextFromET = et.getText().toString();
int nIntFromET = new Integer(sTextFromET).intValue();
OR
try
{
int nIntFromET = Integer.parseInt(sTextFromET);
}
catch (NumberFormatException e)
{
// handle the exception
}
Try this,
EditText x = (EditText) findViewById(R.id.editText1);
int n = Integer.parseInt(x.getText().toString());
You can use parseInt with try and catch block
try
{
int myVal= Integer.parseInt(mTextView.getText().toString());
}
catch (NumberFormatException e)
{
// handle the exception
int myVal=0;
}
Or you can create your own tryParse method :
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
and use it in your code like:
int myVal= tryParse(mTextView.getText().toString());
Note: The following code without try/catch will throw an exception
int myVal= new Integer(mTextView.getText().toString()).intValue();
Or
int myVal= Integer.decode(mTextView.getText().toString()).intValue();
Try the line below to convert editText to integer.
int intVal = Integer.parseInt(mEtValue.getText().toString());
I had the same problem myself. I'm not sure if you got it to work though, but what I had to was:
EditText cypherInput;
cypherInput = (EditText)findViewById(R.id.input_cipherValue);
int cypher = Integer.parseInt(cypherInput.getText().toString());
The third line of code caused the app to crash without using the .getText() before the .toString().
Just for reference, here is my XML:
<EditText
android:id="#+id/input_cipherValue"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
You can use like this
EditText dollar=(EditText) findViewById(R.id.money);
int rupees=Integer.parseInt( dollar.getText().toString());
First, find your EditText in the resource of the android studio by using this code:
EditText value = (EditText) findViewById(R.id.editText1);
Then convert EditText value into a string and then parse the value to an int.
int number = Integer.parseInt(x.getText().toString());
This will work
int total_Parson = Integer.parseInt(etRegularTickets.getText().toString());
int ticket_price=Integer.parseInt(TicketData.get(0).getTicket_price_regular());
total_ticket_amount = ticket_price * total_Parson;
etRegularPrice.setText(""+total_ticket_amount);
In Kotlin, you can do this.
val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()
In kotlin, there is shortest way thanks to the Extension Function
fun EditText.toInt(): Int {
return this.text.toString().toInt()
}
Use it in your code like below:
mEditText.toInt()

Categories

Resources