public void click(View view) {
String one = "one";
EditText et = (EditText)findViewById(R.id.editText1);
String entered_text = et.getText().toString();
if(et.getText().toString() == one){
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Correct!");
}
else {
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(one+entered_text); }
}
This is a code snippet extracted from my program, I didn't post the whole program because it wasn't necessary, as the program runs fine without any runtime exceptions.
So, the program when executed on Eclipse doesn't show any errors and runs fine, but when run the, if condition et.getText().toString() == "one" always returns false even when the entered_text is one i.e.; it never prints "correct!" and the code always prints "one+entered_text" that is the statement in the else clause. And the interesting point is, if you enter one the output will be oneone, that is the else statement.
Please help me where I went wrong.
Thanks in advance.
Try this
if(et.getText().toString().equals(one)){
instead of
if(et.getText().toString() == one){
the better way is to compare string like et.getText().toString().equals("one");
also do et.getText().toString().trim().equals("one"); to avoid spaces error
Related
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"){
I have the following code:
public void click(View v)
{
Button b = (Button) v;
TextView viewEditText = (TextView) findViewById(R.id.functionTextView);
String editText = viewEditText.getText().toString();
if (b.getId() == R.id.backspace)
{
if (viewEditText.length() > 0)
{
if (editText.substring(editText.length() - 1, editText.length()) == ".")
{
periodTrue = false;
}
viewEditText.setText(viewEditText.getText().toString().substring(0, viewEditText.length() - 1));
}
}
}
In this code I check to see if the character being backspaced is a period, if the previous condition is true. It sets the variable periodTrue to false. This tells the app that another period can be added.
Everything works with the backspace key as normal, except it never makes it inside the if statement where the variable is set. It throws no errors and I have checked with
viewEditText.append(editText.subString(editText.length()-1, editText.length()); to verify that the returned character is ".".
I don't know why it's not working, and it throws no errors or warnings either, on compile or run time. So I've come to you to see if a different perspective can show what I'm obviously doing wrong.
if (editText.substring(editText.length() - 1, editText.length()) == ".")
This won't work as you're comparing the references of the two Strings, which will be different. (More in-depth explanation in this question: How do I compare strings in Java?)
Use the following instead:
if (".".equals(editText.substring(editText.length() - 1, editText.length())))
et = (EditText) findViewById(R.id.editText1);
iv = (ImageView) findViewById(R.id.imageView1);
Case R.id.ibGo:
String str = et.getText().toString();
if (str.contentEquals("password")){
Intent levelTwo = new Intent (
"com.xxx.xxx.LEVELTWO");
startActivity(levelTwo);
} else if (str.contentEquals("music")){
Intent levelFour = new Intent (
"com.xxx.xxx.LEVELFOUR");
startActivity(levelFour);
} else {
vib.vibrate(300);
iv.setVisibility(View.VISIBLE);
}
break;
When i write "password" in the edittext in the emulator, the emulator works as expected. But when i (for example) write "Passwords"(Capital P) the application stops unexpectedly.
What can I do to make it not fail on capital letters?
Strings are case sensitive.
Instead of
if (str.contentEquals("password")){
//do something
}
DO THIS!!
if (str.equalsIgnoreCase("password")){
//do something
}
I think your question and your problem are two different things, so:
What can I do to make it not react to capital letters, ways to make it not case sensetive?
You can use equalsIgnoreCase (str.equalsIgnoreCase("password")) to make the comparison case insensitive, but I think your problem is here:
But when i for example write "Passwords"(Capital P) the application stops unexpectedly..
This is probably due to a problem in the else block, seems like either vib or iv are null.
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
I have a button that sends message - however the onClick feature in the onClickListener seems to give me a few errors when I tell it to disable the button when click, AND when I set toast to it. Oh, and the error underlines 'else' saying syntax error. (Other than that the code works fine and sends the SMS)
public void onClick(View v)
{
messageinfo mi = new messageinfo();
String message = txtMessage.getText().toString();
if (message.length()>0)
sendSMS(mi.SMSNO(), smsmessage);
Toast.makeText(getBaseContext(), "sending", Toast.LENGTH_SHORT).show();
myButton.setEnabled(false);
else
Toast.makeText(getBaseContext(), "enter your message", Toast.LENGTH_SHORT).show();
}
Is there an easy solution to this?
Through formatting your code I've noticed that it would appear that your if statement is failing.
You need to have { }s around the resulting code from an if statement, eg:
if(true){
line 1;
line 2;
line 3;
}
else {
line 1;
line 2;
line 3;
}
The only time you can miss out the { }s is when you've only got ONE statement following an if. This is always a bad idea however, its not much effort just to put in some { }s, and means that issues like this won't ever happen.
Clarification
The code in your question is running the if and if it matches it runs THE NEXT LINE. Then the code carries on OUTSIDE of the if clause (because of missing brackets)so then will run the next two lines REGARDLESS of the outcome of the if statement.
Then it encounters the else which its not expecting. Its supposed to be after either { .. } or directly after the FIRST statement after the if, so that's why it fails at the else.