i need a favor.. i'm confused to put these codes to check whether the edittext is empty or not:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
where must i write these codes? is it between these codes?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuawal);
...
...
...
JmlAhliWarisAnakLK = (EditText) findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
or in this function after double sisa=0;??
public void cc() {
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
int JmlWarisAnakLK = Integer.parseInt(JmlAhliWarisAnakLK.getText().toString());
int JmlHarta = Integer.parseInt(JmlHartaPeninggalan.getText().toString());
double HasilSuami = 0;
double HasilIstri = 0;
double HasilAnakLK = 0;
double HasilAnakPR = 0;
double sisa = 0;
}
please correct me if i'm wrong.. :D
you are on the right track
After you set the layout using setContentView you need to add your EditText's which you are doing fine as follows.
JmlAhliWarisAnakLK = (EditText)findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
You then need to store the value you get from the EditText's in some variable,
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
....
....
After you have stored your values you can then call some method that validates your input on click of a button(if you have):
public void validateinput()
{
if(input == null || input.trim().equals(""))
{
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
}
According to me, you should put the check on some event, like if its login screen, then on click of submit button. or other wise on focus change it main instantly provide user with the toast that he left the field empty. or if other case, please provide more information for your query. thanks.
That depends on when you want to validate the editText..You propably have some button which "submits" the EditText so call this code in after onClick event gets fired on the button..
Put the input validation code when you have to navigate away from the current activity, either to go to another activity or to save the input details. That's the least annoying place to shove an error message onto the user.
Another approach is to validate when the focus leaves the EditText. But in this case the error notification should be more subtle (and therefore less annoying) like changing the EditText's background to lightred.
Ur questions does not seem to be clear. Are u asking where do u need to put the validation for empty edittext? If this is ur question then the general case would be to validate during any events such as BUTTON CLICK. Set the onClickListener for ur button and inside ur onclick perform the validation.
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
Your above code is pretty much correct. You Must need to add above code whenever you want to take input from these edittext, Or whenever you want to save these value. make a function which will return true if edit text is empty so u can ask user to enter values
public boolean isETEmpty(){
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
return true;
}
return false; // if not empty
}
call this function Whenever u want to use values from ET, if this function return true, you must let user enter values. Such as on Button Click to save etc
Related
I have a EditText (inputValue) that accepts numberDecimal format, which I need to validate. The validation function is called by:
buttonCalculate.setOnClickListener {
pickFunction() }
If this EditText is left blank I get an immediate program crash after each button click. If I fill in the form with a zero, then click the button, validation works as expected.
fun pickFunction() {
val s: String = inputValue.getText().toString().trim()
val d = inputValue.getText().toString().toDouble()
if(s.isNullOrEmpty()) {
Toast.makeText(applicationContext, "Blank value entered", Toast.LENGTH_SHORT).show()
return
}
if( d <= 0)
{
Toast.makeText(applicationContext, "Zero value entered", Toast.LENGTH_SHORT).show()
return
}
// go do something with valid value
}
button clicks giving you crash because your Edittext doesnt have any value and you call .trim()and .toDouble() on null object reference. Please check null check condition before calling trim and todouble methods.
Use toDoubleOrNull() instead of toDouble() or wrap that line in a try-catch to handle NumberFormatException.
I'm trying to check the editText condition. In the code below, I declared a setOnClickListener method to check the condition of editText. If condition is true, I want to print toast message, change the activity and to output a sound. If condition fails, it should toast a single message. In both cases if it's true or not, it prints me only "Incorect" no matter if editText is correct.
What I am doing wrong?
public void next(View v){
final MediaPlayer correctSound = MediaPlayer.create(this, R.raw.correctsound);
Button playCorrectSound = (Button) this.findViewById(R.id.angry_btn1);
final EditText editTextt = (EditText) findViewById(R.id.editText);
playCorrectSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTextt.setVisibility(View.INVISIBLE);
if(editTextt.getText().toString() == "string")
{
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
correctSound.start();
Intent i = new Intent(Hereuu.this, MainActivity.class);
startActivity(i);
} else {
Context context = getApplicationContext();
CharSequence text = "Incorect";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
editTextt.setVisibility(View.VISIBLE);
}
});
}
Like everyone had said, you
Basically, when you use == operator, your are checking if the reference for object are the same/equals. When you use .equals(String), the method checks the content.
tip:
When your are working with Strings, remember to avoid NullPointerException situations. So,you should write "constant".equals(editTextValue) instead of editTextValue.equals("constant")
The link bellow will help you to understand how String objects and String content work:
Java String.equals versus ==
regards
in java you need to compare strings using equals method instead of ==
check this topic for more details
I would suggest you to take some basic JAVA lessons. That will immensely help you.
For now, the problem is in the way you are checking equality of the strings. You do not use == with strings, you use String#equals() method. So,
Change
editTextt.getText().toString() == "string"
to
editTextt.getText().toString().equals("string")
Make sure to compare strings in java with .equals and not ==. Use this if statement:
if(editTextt.getText().toString().equals("string"){
In eclipse i tried making a calculator. I had 2 separate text fields for two numbers and addition subtraction buttons. When i press add or sub button without entering values app crashes. Is there any possible way out?
public void onClick(View v) {
// TODO Auto-generated method stub
String l1= et1.getText().toString();
String l2= et2.getText().toString();
int a=0, b=0;
double result=0.0;
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
switch(v.getId())
{
case R.id.b1:
result=a+b;
break;
case R.id.b2:
result=a-b;
break;
case R.id.b3:
result = a*b;
break;
case R.id.b4:
if(b==0)
{
open("Cannot Divide By zero");
}
else result = a/b;
break;
}
et3.setText(Double.toString(result));
}
Clayton Oliveira's answer is good. It handles the empty input situation. This code handles all the cases where l1, l2 can not be parsed to integer.
try{
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
} catch(NumberFormatException e) {
Log.e("Wrong input", e.getMessage());
}
If no value was entered in the EditText, the Integer.parseInt() method will crash because the String passed is not a valid number.
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
Replace with:
if(!l1.isEmpty() && !l2.isEmpty()){
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
}else{
Toast.makeText(this,"Something is wrong!",Toast.LENGTH_SHORT).show();
}
Note: the code above only check if was entered something in the EditTexts, you should check if it's a number also. i will leave that part for you to learn ;)
You should post more detail about your code to get many support at here, but i guess you have get this problem:
Add or Sub function net two integer number to calculate but you not enter any value (number value) into Edittext (text field) and value is null or empty string so wrong.
Solution:
- You set edittext to require input number value not string
- you need check input value is empty (if true then do not something) to before calculate.
I've difficulty in creating a validation before saving it to sqlite, below is the code:
public void save(View v){
String weight = weightinputid.getText().toString();
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0){
message.mess(this, "Error");
}
else{
message.mess(this, "BMI has been saved");
}
}
How do I create a validation if all the textfields are empty? my problem right now, even if i pressed the save button, the empty textfields was saved inside the database
You can just try this, to check if value is not entered in the EditText.
if (weight .equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if (bmi.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (status.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value3", Toast.LENGTH_LONG).show();
}
Alternatively, you can use .matches("") instead of .equals("")
UPDATE
As #Rajesh mentioned in his comments, you can also use
TextUtils.isEmpty(weightinputid.getText())
to achieve the same functionality.
You can definitely do #Lal suggestion but in case the N fields are empty it's going to show the N toasts, and that's not very useful:
I'll suggest to do the following one of the following options:
a) Implement MaterialEditText:
Check the details here:
https://github.com/rengwuxian/MaterialEditText
<com.rengwuxian.materialedittext.MaterialEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Min Characters"
app:met_minCharacters="1" />
b) Use a TextWatcher and enable the SaveButton only after you have your required fields with values:
http://developer.android.com/reference/android/text/TextWatcher.html
You can see how to it with the following question:
Disable Button when Edit Text Fields empty
I want to make that when the user click the button below and the String on EditText is empty, it shows a dialog.
So I made this method, but unfortunately rather than showing a Dialog Box, the app crashed. There's no problem with the Dialog box method, the problem is the IF function doesn't read what I requested properly.
Anybody has the solution for this?
Here's my method:
public void onClick(View v) {
if(v == launchSimplePayment) {
String amount = paymentAmount.getText().toString();
System.out.println(amount);
if (amount == "")
{
errorDialog();
}
else
{
System.out.println(amount);
// Use our helper function to create the simple payment.
PayPalPayment payment = exampleSimplePayment();
// Use checkout to create our Intent.
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this, new ResultDelegate());
// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
startActivityForResult(checkoutIntent, request);
}
}
Change this
if (amount == "")
with this
if (amount.equals(""))
Remember that the operator == compares references, not the content!
You should rewrite the condition like this:
if (amount.trim().equals(""))
Since a blank space like this " " would pass over your validation check.