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();
}
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();
}
In this I am trying to validate phone number . but even if i do enter correct number it wont verify. code is below
cont=(EditText)findViewById(R.id.editcontact);
final String MobilePattern = "[0-9]{10}";
btn_log=(Button)findViewById(R.id.button_log);
btn_log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String phn=cont.getText().toString();
if (!phn.matches(MobilePattern)) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
}
});
your regex is proper but you are using it in incorrect way, you need to compile your pattern before using it to match.
String patterntomatch ="[0-9]{10}";
Pattern pattern=Pattern.compile(patterntomatch);
Matcher matcher=pattern.matcher(phn);
if (!matcher.find()) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
} else {
//To get matching text you can use
String ans = phn.substring(matcher.start(), matcher.end());
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
first try
final String phn=cont.getText().toString().trim();
it will help you when your content contains any spaces.
try by changing below things
final String MobilePattern = "[0-9]";
.......
final String phn=cont.getText().toString().trim();
.........
if (!phn.matches(MobilePattern) || phn.length() != 10 ) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
}
Here I am giving you two step simple solution, At the very first allow user only take the valid input.
So use in your XML.
android:digits="0123456789"
android:inputType="phone"
android:maxLength="10"
Hopefully you can easily can understand each line meaning. Secondly you can validate on button click like below is given.
tv_login.setOnClickListener(v -> {
if (!isValidMobile(etPhone.getText().toString())){
//Invalid Mobile Number
}else {
//Valid Mobile Number
}
});
private boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 10 || phone.length() > 10) {
check = false;
} else {
check = true;
}
} else {
check = false;
}
return check;
}
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.
I'm trying to save userName but the saved text file always returns , 6. How can I get it to show whatever value of userName entered into EditText, and the rest? for example Don, 6. I have read you have to use getText() but that isn't returning anything in the saved file.
However, if I replace 6 with an intent to receive score from previous activity, this works! like this...
Bundle extras = getIntent().getExtras();
int score = extras.getInt("Score");
So this becomes...
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("score");
quit.setOnClickListener(new View.OnClickListener() {
String strName = userName.getText().toString();
#Override
public void onClick(View v) {
saveProgress(strName + ", " + score, "results.txt");
finish();
System.exit(0);
}
});
}
But it still returns empty, whatever score is. For example , 4.
I've read this post that suggests it should be inside onClickListener which it is:
EditText getText().toString() not working
This is my saveProgress class:
public void saveProgress(String contents, String fileName) {
try {
File fp = new File(this.getFilesDir(), fileName);
FileWriter out = new FileWriter(fp);
out.append(contents);
out.append("\n\r");
out.close();
}
catch (IOException e) {
Log.d("Me","file error:" + e);
}
}
Change your onClick() method with the following:
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("score");
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = userName.getText().toString();
saveProgress(strName + ", " + score, "results.txt");
finish();
System.exit(0);
}
});
}
Calls, initializations, operations, exc, should go inside the onClick method of the listener. The onClick is fired only when the button is clicked, everything outside the onClick but inside the Listener is called on Listener initialization
I guess you understood 'inside onClickListener' wrong. What you are doing atm is that you read strName when you create the listener, but I guess you want to read it when quit is clicked.
So just move the line into the function and the value will be correct.
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = userName.getText().toString();
saveProgress(strName + ", " + 6, "results.txt");
finish();
System.exit(0);
}
});
}
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.