1
votes
<EditText
    android:id="@+id/edtxt1"
    android:layout_below="@+id/txt1"
    android:layout_width="fill_parent"
    android:gravity="center_horizontal"
    android:maxLength="15"
    android:textColor="#ffffff"
    android:paddingTop="10dp"
    android:layout_marginLeft="30dp"
    android:background="@drawable/edittxt"
    android:inputType="numberDecimal"
    android:layout_centerInParent="true"
    android:layout_height="50dp" />

I have a unit converter app. Everything works fine, but the only problem I have is if the user enter only a decimal point "." in the EditText and tries to convert one parameter to another, the app crashes!

How could I detect if only a decimal point is entered (ie. without the numbers; like "." is entered instead of "3.03" or ".3").

I used the code below to detect if the EditText is empty when the user is trying to convert from one parameter to another, but it doesn't work for decimal point.

if (cel1.matches(""))
{
    Toast.makeText(getApplicationContext(), "Enter the content!",
                                                         Toast.LENGTH_LONG).show();
}
3
if (cel1.equals("") || cel1.equals(".")) ?Elliott Frisch
Please take a look at my answer and give me some feedback on what you want. If it works for you, please accept it.Michael Yaworski

3 Answers

3
votes

Checking for just a decimal point:

EditText et = (EditText)findViewById(R.id.edtxt1);
if (et.getText().toString().equals("."))
{
    // run your code here
}

Using your code:

if (cel1.equals("") || cel1.equals("."))
{
    Toast.makeText(getApplicationContext(), "Enter the content!",
                                                       Toast.LENGTH_LONG).show();
}

Perhaps you want to change cel1.equals(".") to cel1.trim().equals(".") just to make sure the condition works even if there are blank spaces in there as well. I'm not sure if you allow spaces in the first place, though.

1
votes

You could check if only a decimal point is in the EditText:

//Get text from the EditText and check if it's a dot.

if (editText.getText().toString().equals("."))
{
    //display error message
}
0
votes

You can check this:

As u asked about without the numbers,like "." is entered instead of "3.03" or ".3"

EditText edittext1=(EditText)findViewById(R.id.edtxt1)
String cel1= edittext1.getText().toString();

if (cel1.trim().length()!=0 && cel1.startsWith("[.]");)
{
    Toast.makeText(getApplicationContext(), "Wrong content here, please Try again!!",
                                                         Toast.LENGTH_LONG).show();
}