EditText case sensitive - android

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.

Related

Error while checking user input

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"){

Button pressing causes app crash

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.

android how to change from if-else to switch case

I have an application about pmt function. However there are so many conditions that need to be handled. Somehow the app will not work with having more than 12 if-else. I want to use switch case, but i still not really understand how to use switch case(been 1 and half month since my 1st try using eclipse).Any example will be highly appreciated.
here is my example code:
if(String1.toString().equals("condition1")){
//do something
if(String2.toString().equals("condition1.1")&& String3.toString().equals("condition1.2")){
//do something else
}
.
.
.
.
.
if(String2.toString().equals("condition1.##")&& String3.toString().equals("condition1.##")){
//do something else
}
}
else if(String1.toString().equals("condition2")){
//do something
if(String2.toString().equals("condition2.1")&& String3.toString().equals("condition2.2")){
//do something else
}
.
.
.
.
.
if(String2.toString().equals("condition2.##")&& String3.toString().equals("condition2.##")){
//do something else
}
}
if(String1.toString().equals("condition3")){
//do something
if(String2.toString().equals("condition3.1")&& String3.toString().equals("condition3.2")){
//do something else
}
.
.
.
.
.
if(String2.toString().equals("condition3.##")&& String3.toString().equals("condition3.##")){
//do something else
}
}
and still keep going....to handle all possibilities .I am wondering, How to do this in switch case . Or a better implementation if we have 3 times 3 conditions. For example a,b,c(suppose these three conditions can only be used once) and d,e,f and g,h,i then condition 1 is a,d,g ; condition 2 is a,d,h condition 3 is a,d,i ; condition 4 a,e,g........on so on
Note:Suppose that the API version is 8-11 (old android)
thanks
The answer is dependent on your target version of android. From KitKat and upwards (API Level 19+), Java 7's switch (String) is available. I'd also strongly suggest trying to group the subcases (condition n.x) into different methods. It just gets very unwieldly quickly, otherwise:
switch (String1.toString) {
case "condition1":
handleCase1(String2, String3);
break;
case "condition2":
handleCase2(String2, String3);
break;
}
If that still results in too complex code, you can try a lookup table together with a command pattern:
class ConditionKey {
final String String1;
final String String2;
final String String3;
public int hashCode(); // hash strings
public boolean equals(); // compare strings
}
interface ConditionCommand {
// use whatever arguments the operation needs, you can also
// add fields and initialize in the constructor
void perform(final ConditionKey key, /* [...] */);
}
Map<ConditionKey, ConditionCommand> actionMap = new HashMap<>();
actionMap.put(
new ConditionKey("condition1", "condition1.1", "condition1.2"),
new ConditionCommand() {
void perform(final ConditionKey key) {
// perform actions that need to be done
}
}
);
And then instead of the if-else or switch-case:
[...]
ConditionKey key = new ConditionKey(string1, string2, string3);
// get the action from the map
ConditionCommand command = actionMap.get(key);
// perform the command
command.perform(key);
since java 1.7 switch on string is supported.
you could annidate two switch:
switch(String1) {
case "condition1": {
switch(String2) {
case "condition1.1":
break;
// ... other cases
default:
break;
}
}
break;
// ... other cases
default break;
}

how to validate the edittext fields using switch case instead of if-else condition in android?

Previously i am using if else condition for checking the edit text field its working but i need to change into switch case.I am not getting to implement switch case inside my code.please tell me how to implement that in switch case.
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
/**
* Validation
*/
if(tvStartLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter start location", Toast.LENGTH_SHORT).show();
}
else if(tvEndLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter end location", Toast.LENGTH_SHORT).show();
}
else if(etStartOdometer.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Trip Start Odometer reading", Toast.LENGTH_SHORT).show();
}
else
{
gotonextfraggment();
}
You cannot use a switch-case construct in your case. In a switch-case, only one argument is matched with the case labels and if there is a match, that label is executed.
switch(arg) {
case "label1":
case "label2":
.
.
.
default:
}
arg is tested with label1, label2 and so on.
In your case, in every else-if, you are trying to test the equality of the text in different EditTexts with "". So your arg changes in every else-if. Even if you try to implement switch-case, the arg of your switch-case will change continuously and you'll not be able to go any further. You cannot even do this:
switch("") {
case edittext1.getText():
case edittext2.getText();
.
.
.
default:
}
Because the case labels must be literals not variable values.
So it is impossible to implement switch-case for the problem that you are facing
In fact what you've done right now is the perfect way to do it.

Need help in my program in eclipse

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

Categories

Resources