I have 2 buttons for the quality. If the quality is set by typing first, the buttons work well, but if I don't write any quantity and I want to set it by plus button, the app crash.
increaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
quantity.setText(String.valueOf(givenQuantity + 1));
}
});
decreaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
//To validate if quantity is greater than 0
if ((givenQuantity - 1) >= 0) {
quantity.setText(String.valueOf(givenQuantity - 1));
} else {
Toast.makeText(EditorActivity.this, R.string.quantity_no_less_then_0, Toast.LENGTH_SHORT).show();
return;
}
}
});
Surround all your parsing lines with try/catch, like:
try {
givenQuantity = Integer.parseInt(textQuantity);
} catch (NumberFormatException e) {
e.printStackTrace();
givenQuantity = 0;
}
when the EditText is empty, a NumberFormatException is thrown because an empty string can not be parsed to int.
check is edittext is empty or not. If empty show toast message to user asking to enter some value to calculate.
Related
I want to check if user input is equal to the array, if not toast error message when pressing a button. I am not sure if I should check input outside the button and then use an if !equals inside button to toast the message. Here is my attempt
I have this array in strings.xml
<string-array name="people">
<item>JHON</item>
<item>MARIE</item>
<item>ALBERT</item>
<item>ALEX</item>
</string-array>
Activity.java:
String[] peopleArr =getResources().getStringArray(R.array.people);
EditText userinput=findViewById(R.id.editTextUserinput);
Button find = findViewById(R.id.findBtn);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i <= peopleArr.length - 1; i++) {
if (!userinput.getText().toString().equals(peopleArr[i])) {
Toast.makeText(getApplicationContext(), "Invalid user", Toast.LENGTH_SHORT).show();
}
}
}
This is wrong because it is toasting invalid user 4 times when the button is pressed.
this code check user, if can finde user will Toast: Valid User otherwise will Toast: Invalid User
String[] peopleArr =getResources().getStringArray(R.array.people);
EditText userinput=findViewById(R.id.editTextUserinput);
Button find = findViewById(R.id.findBtn);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean userIsFounded = false;
for (int i = 0; i <= peopleArr.length - 1; i++) {
if (userinput.getText().toString().equals(peopleArr[i])) {
userIsFounded = true;
break;
}
}
String message = (userIsFounded)? "Valid User":"InValid User";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
I'm trying to check if a string is alphanumeric or not. I tried many things given in other posts but to no avail. I tried StringUtils.isAlphanumeric(), a library from Apache Commons but failed. I tried regex also from this link but that too didn't worked. Is there a method to check if a string is alphanumeric and returns true or false according to it?
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = fullnameet.getText().toString();
String numRegex = ".*[0-9].*";
String alphaRegex = ".*[A-Z].*";
if (text.matches(numRegex) && text.matches(alphaRegex)) {
System.out.println("Its Alphanumeric");
}else{
System.out.println("Its NOT Alphanumeric");
}
}
});
If you want to ascertain that your string is both alphanumeric and contains both numbers and letters, then you can use the following logic:
.*[A-Za-z].* check for the presence of at least one letter
.*[0-9].* check for the presence of at least one number
[A-Za-z0-9]* check that only numbers and letters compose this string
String text = fullnameet.getText().toString();
if (text.matches(".*[A-Za-z].*") && text.matches(".*[0-9].*") && text.matches("[A-Za-z0-9]*")) {
System.out.println("Its Alphanumeric");
} else {
System.out.println("Its NOT Alphanumeric");
}
Note that we could handle this with a single regex but it would likely be verbose and possibly harder to maintain than the above answer.
Original from here
String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));
String myString = "qwerty123456";
if(myString.matches("[A-Za-z0-9]+"))
{
System.out.println("Alphanumeric");
}
if(myString.matches("[A-Za-z]+"))
{
System.out.println("Alphabet");
}
try this
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(edittext.getText().toString()).find();
if (!edittext.getText().toString().trim().equals("")) {
if (hasSpecialChar) {
Toast.makeText(MainActivity.this, "not Alphanumeric", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Its Alphanumeric", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Empty value of edit text", Toast.LENGTH_SHORT).show();
}
}
});
This is the code to check if the string is alphanumeric or not. For more details check Fastest way to check a string is alphanumeric in Java
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the https://www.nuget.org/packages/Extensions.cs package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Your example code would become as simple as:
using Extensions;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = fullnameet.getText().toString();
//String numRegex = ".*[0-9].*";
//String alphaRegex = ".*[A-Z].*";
//if (text.matches(numRegex) && text.matches(alphaRegex)) {
if (text.IsAlphaNumeric()) {
System.out.println("Its Alphanumeric");
}else{
System.out.println("Its NOT Alphanumeric");
}
}
});
I want to get a number from editText and use in a calculation, there is no any error in my code but I didn't get what I looking for, the value of r is alwayas 1, here is the code:
public class Counter extends Activity {
Button add, sub;
TextView result;
EditText range;
double r;
public double c=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
add = (Button) this.findViewById(R.id.add);
sub = (Button) this.findViewById(R.id.sub);
result = (TextView) this.findViewById(R.id.result);
range = (EditText) this.findViewById(R.id.range);
try {
r = new Double(range.getText().toString());
} catch (NumberFormatException e) {
r = 1; // your default value
}
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
c=c+r;
result.setText(""+c);
}
});
sub.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
c=c-r;
result.setText(""+c);
}
});
}
any help ??
try {
r = new Double(range.getText().toString());
} catch (NumberFormatException e) {
r = 1; // your default value
}
the snippet of code you posted is correct. Double has a constructor that takes a String . The problem is that you are executing it after your findViewById and probably the EditText does not contain nothing. For instance when you press on add, you can retrieve the content of the EditText again and parse it:
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
r = new Double(range.getText().toString());
} catch (NumberFormatException e) {
r = 1; // your default value
}
c=c+r;
result.setText(""+c);
}
});
Double class provides a static method which parses a string to double.
So try to change:
r = new Double(range.getText().toString());
To:
r = Double.parseDouble(range.getText().toString());
Additionally, you may want to parse other strings to other types of numbers such as integers:
int x = Integer.parseInt(yourString);
Try this (parsing string to double):
r = Double.parseDouble(range.getText().toString());
you should get value from EditText when user will click on button when you will get value only in onCreate() it will be take data from EditText when it will be created
You need to use Double.parseDouble(range.getText().toString());
You just need to do:
r = Double.parseDouble(range.getText().toString()); // Surround with try/catch for fancy functionality
use like that:
r=Double.parseDouble(range.getText().toString());
Try this one: Just in case there is the possibility that the String from the EditText cannot be parsed to a double I have put it inside a try-catch block.
double r;
try {
r = Double.parseDouble(range.getText().toString());
catch (NumberFormatException ex) {
r = 1;
}
Hope this helps :)
you can make your editText in the XML file so that it accepts only numbers
android:inputType="number"
and in your java code
r = Double.parseDouble(range.getText().toString());
This question already has answers here:
How do I check if my EditText fields are empty? [closed]
(30 answers)
Closed 9 years ago.
My code does not print empty edit text itry trim stirng .length==00 but is not work hat wrong in my code?? how do my code check if edittext is empty before sumbit query
I want to check before submit method if edittext is empty? If is empty then print toast message
public class AgAppTransPayExternalAccount extends Activity {
TextView lblTPEAWelcomeToPayExternalAccountPage;
TextView lblTPEAOtherAccount;
TextView lblTPEAPinno;
TextView lblTPEAAmount;
EditText txtTPEAotheraccount;
EditText txtTPEApinno;
EditText txtTPEAamount;
Button btnTPEAsubmit;
Button clearTPEAButton;
Button btnTPEAgoback;
String sms;
public static ProgressDialog PayExternalAccountProgressDialog = null;
public static boolean value=true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapptranspayexternalaccount);
sms=LoginScreen.item.toString();
/*
lblTPEAWelcomeToPayExternalAccountPage = (TextView)
findViewById(R.id.lblTPEAWelcomeToPayExternalAccountPage);
lblTPEAWelcomeToPayExternalAccountPage.setText("Welcome To Pay External
Account Page");
lblTPEAWelcomeToPayExternalAccountPage.setTextColor(getResources().getColor
(R.color.text_color_black));
*/
lblTPEAOtherAccount = (TextView) findViewById(R.id.lblTPEAOtherAccount);
lblTPEAOtherAccount.setText("Other Account :");
txtTPEAotheraccount=(EditText) findViewById(R.id.txtTPEAotheraccount);
lblTPEAPinno = (TextView) findViewById(R.id.lblTPEAPinno);
lblTPEAPinno.setText("PIN Number :");
txtTPEApinno=(EditText) findViewById(R.id.txtTPEApinno);
lblTPEAAmount = (TextView) findViewById(R.id.lblTPEAAmount);
lblTPEAAmount.setText("Amount :");
txtTPEAamount=(EditText) findViewById(R.id.txtTPEAamount);
btnTPEAsubmit=(Button) findViewById(R.id.btnTPEAsubmit);
btnTPEAsubmit.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton=(Button) findViewById(R.id.clearTPEAButton);
clearTPEAButton.setTextColor(getResources().getColor(R.color.text_color_blue));
btnTPEAgoback=(Button) findViewById(R.id.btnTPEAgoback);
btnTPEAgoback.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
txtTPEAotheraccount.setText("");
txtTPEApinno.setText("");
txtTPEAamount.setText("");
}
});
btnTPEAgoback.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
btnTPEAsubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String tpeapinemptycheck = txtTPEApinno.getText().toString();
String otheraccountemptycheck =
lblTPEAOtherAccount.getText().toString();
String amountemptycheck = txtTPEAamount.getText().toString();
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
showProgress();
submitPEA();
}
});
}
private void submitPEA() {
String message;
String mobilenumber= LoginScreen.smsmobileno;
if (( sms.compareTo("SMS")==0))
{
SmsManager smsmanager = SmsManager.getDefault();
message="AGPEA"+AgAppHelperMethods.varMobileNo+AgAppHelperMethods.
arMobileNo+txtTPEAotheraccount.getText().toString()+AgAppHelperMethods.
varMobileNo+txtTPEApinno.getText().toString()+txtTPEAamount.getText().toString();
smsmanager.sendTextMessage(mobilenumber, null, message, null, null);
}
else
{
Intent j = new Intent(AgAppTransPayExternalAccount.this, AgAppTransPEAResponse.class);
Bundle bundle = new Bundle();
bundle.putString("txtTPEApinno", txtTPEApinno.getText().toString());
bundle.putString("txtTPEAotheraccount",txtTPEAotheraccount.getText().toString());
bundle.putString("txtTPEAamount",txtTPEAamount.getText().toString());
j.putExtras(bundle);
startActivity(j);
value=false;
PayExternalAccountProgressDialog.dismiss();
}
}
private void showProgress()
{
PayExternalAccountProgressDialog =
ProgressDialog.show(AgAppTransPayExternalAccount.this,null, "Processing please
wait...", true);
if (PayExternalAccountProgressDialog != null) {
try
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
PayExternalAccountProgressDialog.dismiss();
if(value)
{
Toast.makeText(AgAppTransPayExternalAccount.this, "Request
TimeOut " , Toast.LENGTH_SHORT).show();
}
}
}, 15000); // <--- here is the time adjustment.
}
catch (Exception e)
{
}
}
}
}
Your code is right, only missing this is { } braces in the else condition, try out as following,
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
{ // add this
showProgress();
submitPEA();
} // add this
Just because you haven't added those { } braces, your control was going into submitPEA() method.
Try like this
edit_text.getText().toString().trim().equals("");
Create a String variable say x;
Now if et is your EditText field use this:
x = et.getText().toString();
if the EditText field has any text in it it would be passed to the string x.
Now to check if the string x is not null or contains nothing use
if(x.matches(""))
{
//your code here
}
else
{
//the counter action you'll take
}
this way you can check that the entry you are about to enter in the database won't be empty.
Happy coding.
btnNadoplata.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
if (text1.getText().length() == 14 ) {
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:*123*" + inputValue1 + encodedHash)));
}else {
Toast.makeText(bonbon.this, "Krivi kod. Unesi 14-znamenkasti kod sa bona!", Toast.LENGTH_SHORT).show();
}
}
});
I have one editText, in wich user needs to input a number14 digit number. If number is less or more than an 14 digits, when user clikc on button, he gets the message that say input is not good. The problem is when editText is empty, and user click on button, app crashes. how can i change this, so if editText is empty, user gets message from above code part ??
Sory for my bad english.
It might crash on this line:
long inputValue1 = Long.parseLong(text1.getText().toString());
In fact, if you have an empty string in your EditText text1, the function parseLong() will throw a NumberFormatException exception.
You should test the value of the text of text1 before continuing:
public void onClick(View v)
{
if (text1.getText().toString().compareTo("") == 0)
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
...
Or you can add try/catch instruction to catch the exception thrown by Long.parseLong().
public void onClick(View v)
{
try
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
...
}
catch (NumberFormatException nfe)
{
...
}
You should test your input length before parsing. Parsing crashes.
public void onClick(View v)
{
if( text1.getText().length() <14 )
{
Toast.makeText(bonbon.this, "Krivi kod. Unesi 14-znamenkasti kod sa bona!", Toast.LENGTH_SHORT).show();
return;
}//if
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:*123*" + inputValue1 + encodedHash)));
}//met
An alternative could be to surround parsing with a try/catch/block, but it's less efficient than this simple test, but more robust if user types non digits.
Regards,
Stéphane
objText = (EditText)findViewById(R.id.txtPurchasePrice);
String strPurchasePrice = objText.getText().toString();
objText = (EditText)findViewById(R.id.txtSalePrice);
String strSalePrice = objText.getText().toString();
objText = (EditText)findViewById(R.id.txtShares);
String strShares = objText.getText().toString();
if(strPurchasePrice.trim().equals("") && strSalePrice.trim().equals("") && strShares.trim().equals("")) {
Toast.makeText(getApplicationContext(), "Please insert the Values..", 10000).show();
}