Check for Empty EditText fails - android

I've tried everything from matching strings, to using TextUtils.isEmpty. No matter what I do, b is always true (even when edittext is purposely left blank) which allows the code to proceed to the next steps (this is a Madlib app).
If anybody can see why the code isn't properly checking for blank edittext's and displaying the Please Fill In All Fields" toast when one is blank, it would be very appreciated. Thanks. Sorry for the messy code.
public class Madlibs extends Fragment {
switch (((MainActivity) getActivity()).getStory()) {
case 0:
output.setText(Stories[0]);
title = Titles[0];
actionBar.setTitle(title);
editTextNumber = 12;
addEdit = new BootstrapEditText[editTextNumber];
for (int i = 0; i < addEdit.length; i++) {
addEdit[i] = new BootstrapEditText(getActivity());
l_layout.addView(addEdit[i]);
params.setMargins(0, 20, 0, 20);
addEdit[i].setLayoutParams(params);
addEdit[i].setId(i);
}
addEdit[0].setHint("Name of Sickness");
addEdit[1].setHint("Adjective");
addEdit[2].setHint("Name of Boy");
addEdit[3].setHint("Body Part");
addEdit[4].setHint("Color");
addEdit[5].setHint("Animal");
addEdit[6].setHint("Article of Clothing");
addEdit[7].setHint("Relative");
addEdit[8].setHint("Adjective");
addEdit[9].setHint("Article of Clothing");
addEdit[10].setHint("Body Part");
addEdit[11].setHint("Number");
break;
case 1:
// fragment = new Madlibs();
break;
case 2:
// fragment = new MadlibsSaved();
}
convert = (BootstrapButton) view.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i;
String s;
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else
{
b = true;
}
}
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
}
});

Your problem is here
if (b = true) { // HERE
gather();
postIt();
outputText = output.getText().toString();
}
You are using b = true which sets b to true, and since you are able to do this successfully, the conditional evaluates to true every time. What you want instead is the comparison operator ==
if (b == true) {
gather();
postIt();
outputText = output.getText().toString();
}
or even better, since the variable you are comparing is a boolean, you could just use
if (b) {} //This is "if b is true..."
if (!b) {} //This is "if b is false..."
You can see another one of my answers about this here.

for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else {
b = true;
}
}
For Loop ends here and the following is outside the For Loop :
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
Problem 1 :
if(b == true) {
}
Problem 2 :
Now, suppose edittext 1 is empty, b is set to true but then it'll straightaway move ahead in the loop to edittext 2 to the last edittext which are not empty hence it'll set b to false again. You'll need to put the check inside the for loop.

Related

Calling on click listener multiple times for updating text views?

In my activity i am showing user a question and 3 options to choose from, these options are text-views.
On clicking the text-view On click listener is performed which updates the text-views according to the option selected.
Now user again after reading the question performs on click listener on options. But this is working only twice then it stops clicking and updating.
Debug is not working either i am beginner so i am confused.
#Override
public void onClick(View v) {
int id = v.getId();
if(id == R.id.optionA) {
Answer = optionA;
LogAnswer = "a : " + optionA;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
else if (id == R.id.optionB) {
Answer = optionB;
LogAnswer = "b : " + optionB;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
else if (id == R.id.optionC) {
Answer = optionC;
LogAnswer = "c : " + optionC;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
}
conditions method change text-views according to option.
public void conditions(int i){
if(Answer.equals(optionA) && i == 1 )
{
questionnumber = 2;
MartialStatus = Single;
GetQuestion(2);
}
else if(Answer.equals(optionB) && i == 1 )
{
questionnumber = 2;
GetQuestion(2);
}
}
It may be that my text-view onclicklistener is calling same text-view listener which breaks.

Xamarin - error message displayed in wrong position in RecyclerView

I have validate method inside my RecyclerView Adapter , this method made to validate row before add new row to my adapter , the issue I face when I edit in last row validation error appear in wrong position , I trace my adapter and I am sure it give right position
here is image for reference
my code I check if focused item is last item and validation is passed to add new row
private void CheckNewItemAddMethod(int position)
{
if (Validate(position) && position == ItemCount - 1)
{
transactionItemModelList.Add(new TransactionItemModel() { ItemID = -1 });
NotifyItemInserted(transactionItemModelList.Count - 1);
}
}
private bool Validate(int pos)
{
ItemCustomViewHolder Passedholder = FindViewHolderByPoistion(pos);
bool valid = true;
int x = 0;
if (! int.TryParse(Passedholder.itemCount.Text, out x) || x == 0){
valid = false;
}
int intItemPrice = 0;
if (string.IsNullOrEmpty(Passedholder.itemName.Text) || !int.TryParse(Passedholder.itemPrice.Text, out intItemPrice) || intItemPrice == 0)
{
valid = false;
Passedholder.itemName.SetError(mContext.GetString(Resource.String.empty_field), null);
}else
{
Passedholder.itemName.SetError((string)null, null);
}
if (string.IsNullOrEmpty(Passedholder.itemPrice.Text))
{
valid = false;
Passedholder.itemPrice.SetError(mContext.GetString(Resource.String.empty_field), null);
}
else
{
Passedholder.itemPrice.SetError((string)null, null);
}
return valid;
}
Note when I scroll it back to right view
any one can guide me why that happen

LUHN credit-card validation fails on a valid card number

In my application i want to check whether the user have entered valid card number for that i have used LUHN algorithm.I have created it as method and called in the mainactivity. But even if i give valid card number it shows invalid.While entering card number i have given spaces in between i didn't know because of that its not validating properly. Please help me in finding the mistake.
CreditcardValidation.java
public class CreditcardValidation {
String creditcard_validation,msg;
//String mobilepattern;
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=16 ) && (getSize(number)<=19 )) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp / 10) * 2);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 4) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
public String creditcardvalidation(String creditcard)
{
Scanner sc = new Scanner(System.in);
this.creditcard_validation= creditcard;
long input = 0;
input = sc.nextLong();
//long input = sc.nextLong();
if (isValid(input) == true) {
Log.d("Please fill all the column","valid");
msg="Valid card number";
}
else{
Log.d("Please fill all the column","invalid");
msg="Please enter the valid card number";
}
return msg;
}
}
MainActivity.java
addcard.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.getId()==R.id.btn_add)
{
creditcard= card_number.getText().toString();
cv = new CreditcardValidation();
String mob = cv.creditcardvalidation(creditcard);
Toast.makeText(getActivity(), mob, 1000).show();``
refer code below
EditText cardNumber=(EditText)findViewById(R.id.cardNumber);
String CreditCardType = "Unknown";
/// Remove all spaces and dashes from the passed string
String CardNo ="9292304336";///////cardNumber.getText().toString();
CardNo = CardNo.replace(" ", "");//removing empty space
CardNo = CardNo.replace("-", "");//removing '-'
twoDigit=Integer.parseInt(CardNo.substring(0, 2));
System.out.println("----------twoDigit--"+twoDigit);
fourDigit=Integer.parseInt(CardNo.substring(0, 4));
System.out.println("----------fourDigit--"+fourDigit);
oneDigit=Integer.parseInt(Character.toString(CardNo.charAt(0)));
System.out.println("----------oneDigit--"+oneDigit);
boolean cardValidation=false;
// 'Check that the minimum length of the string isn't <14 characters and -is- numeric
if(CardNo.length()>=14)
{
cardValidation=cardValidationMethod(CardNo);
}
boolean cardValidationMethod(String CardNo)
{
//'Check the first two digits first,for AmericanExpress
if(CardNo.length()==15 && (twoDigit==34 || twoDigit==37))
return true;
else
//'Check the first two digits first,for MasterCard
if(CardNo.length()==16 && twoDigit>=51 && twoDigit<=55)
return true;
else
//'None of the above - so check the 'first four digits collectively
if(CardNo.length()==16 && fourDigit==6011)//for DiscoverCard
return true;
else
if(CardNo.length()==16 || CardNo.length()==13 && oneDigit==4)//for VISA
return true;
else
return false;
}
also u can refer this demo project
Scanner.nextLong() will stop reading as spaces (or other non-digit characters) are encountered.
For instance, if the input is 1234 567 .. then nextLong() will only read 1234.
However, while spaces in the credit-card will [likely] cause it to fail LUHN validation with the above code, I make no guarantee that removing the spaces would make it pass - I'd use a more robust (and well-tested) implementation from the start. There is no need to rewrite such code.

Avoid exception when there is no integer number filled in the edit text

I'm working with Android app, I have 5 edit text, and 1 button to sum the integer number from those edit text. Sometime user can let several edit text blanks. The problem is when the user let it blank, the exception will arise and I don't have any idea to handle it. These are my code
try
{
if (qty1 != null)
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
qty1.setText("0");
}
if (qty2 != null)
{
int jml2 = Integer.parseInt(qty2.getText().toString());
item2 = hrg2 * jml2;
}
else
{
qty2.setText("0");
}
if (qty3 != null)
{
int jml3 = Integer.parseInt(qty3.getText().toString());
item3 = hrg3 * jml3;
}
else
{
qty3.setText("0");
}
if (qty4 != null)
{
int jml4 = Integer.parseInt(qty4.getText().toString());
item4 = hrg4 * jml4;
}
else
{
qty4.setText("0");
}
if (qty5 != null)
{
int jml5 = Integer.parseInt(qty5.getText().toString());
item5 = hrg5 * jml5;
}
else
{
qty5.setText("0");
}
int hasil = item1 + item2 + item3 + item4 + item5;
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
total.setText(String.valueOf(hasil));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Quantity can't be empty. Please type item quantity", Toast.LENGTH_LONG).show();
}
I have try to put condition with if but it doesn't help much. Thanks.
Try this,
if (qty1.getText().toString() != null && !(qty1.getText().toString().equals("")))
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
instead of,
if (qty1 != null)
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
This condition if (qty1 != null) checks if your editText is null but it doesn't check the data contained in it.
Repeat the same for all the other editText values.
put this condition
String s1= qty5.getText().toString().trim();
if(TextUtils.isEmpty(s1)) ///// isEmpty() <-----
{
// error message
}
else
{
// your code
}
If qty1 is yout edittext then you need to get the string from your edittext to check whether it is null or not.
So Change your all edittexts code as like this
if (qty1.getText().toString() != null && qty1.getText().toString().equals(""))
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
qty1.setText("0");
}

How to I finish the "continue;" That i putted after the if statement?

I made a statement and if it is true it continues, I want to stop this "continue" and make another statement for example touchdown and touchup.
here is my code
private void updateRunning(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type != TouchEvent.TOUCH_UP)
continue;
world.doodle.DOODLE_Y = 3;
touchPoint.set(event.x, event.y);
guiCam.touchToWorld(touchPoint);
if (OverlapTester.pointInRectangle(pauseBounds, touchPoint)) {
Assets.clicks();
state = GAME_PAUSED;
return;
}
}
world.update(deltaTime, game.getInput().getAccelX());
if (world.score != lastScore) {
lastScore = world.score;
scoreString = "" + lastScore;
}
if (world.state == World.WORLD_STATE_NEXT_LEVEL) {
state = GAME_LEVEL_END;
}
if (world.state == World.WORLD_STATE_GAME_OVER) {
state = GAME_OVER;
if (lastScore >= Settings.highscores[4])
scoreString = "new highscore: " + lastScore;
else
scoreString = "score: " + lastScore;
Settings.addScore(lastScore);
Settings.save(game.getFileIO());
}
}
Little confused by what you are asking, but perhaps an else if?
if (event.type == TouchEvent.TOUCH_UP) {
/* do something for TOUCH_UP event */
} else if (event.type == TouchEvent.TOUCH_DOWN) {
/* do something for TOUCH_DOWN event */
} else {
/* do something else */
}
You can't stop a continue after you execute it.
Try adding break; where you want it to stop.

Categories

Resources