I have some if statements, I do not know how to show the result on the screen.
Below are 2 things I have tried. I know the system.out goes to the log.
if (Enter == "1") {
// tv.setText("This is the display 1");
System.out.println("The 1");
}
else if (Enter == "2") {
System.out.println("The 2");
}
What is Enter? If it is an instance of an object, use lowercase names, so that would be enter.
To answer the question, you're probably comparing Strings. You should use .equals instead of ==.
So:
String enter = "1"; //your variable
if(enter.equals("1")){
System.out.println("The 1");
}else if(enter.equals("2"){
System.out.println("The 2");
}
When comparing primitive data types (like int, char, boolean) you can use ==, !=, etc.
When comparing objects (like String, Car, etc) you need to use the .equals() method.
See also this page.
Edit
Use a Toast:
Toast.makeText(this, "The 1", Toast.LENGTH_SHORT).show();
See here.
Do it with a Toast instead.
A Toast is a popup-like element in Android displaying a short message for a predefined duration on screen.
String enter = "whatever value enter has";
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
String message = "The Nothing";
if (enter.equals("1")) {
message = "The 1";
} else if (enter.equals("2")){
message = "The 2";
}
Toast messageToast = Toast.makeText(context, message, duration);
messageToast.show();
Related
I am making a unit converter, but if I do not enter any value into edit text and press the calculate button the app crashes with error Invalid float: "". Also, I want to forbid zeroes from being entered before numbers (eg. 0300). How do I accomplish this?
//handle calculate
calcButton=(Button)findViewById(R.id.calcButton);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Spinner spinner = (Spinner) findViewById(R.id.unit_spinner);
String spinnerText = spinner.getSelectedItem().toString();
EditText unit_edit = (EditText) findViewById(R.id.unit_edit);
amount = Float.valueOf(unit_edit.getText().toString());
if (unit_edit.getText().toString().equals(null)) {
Toast.makeText(getApplicationContext(), "Insert Value To Convert",
Toast.LENGTH_LONG).show();
} else {
switch (spinnerText) {
case "Kilograms":
kilograms = amount;
grams = amount * 1000;
ListView();
break;
case "Grams":
grams = amount;
kilograms = amount / 1000;
ListView();
break;
}
}
}
});
}
You are probably getting an NumberFormatException thrown since the EditText fields text is "" and "" is not a valid float value, the exception is thrown at the following line:
amount = Float.valueOf(unit_edit.getText().toString());
What you'll need to do is add some validation and checking before trying to get the float value of a String.
Check the methods documentation for more details http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)
This might be useful for your EditText to limit input to numbers only.
<EditText
android:id="#+id/unit_edit"
android:inputType="number"
/>
You can also limit the digits, type of number such as decimal
<EditText
android:id="#+id/unit_edit"
android:digits="0123456789."
android:inputType="numberDecimal"
/>
You can't parse an empty value to float. You should first test if it's empty, and then do what you want, something like this:
String text = unit_edit.getText().toString();
if(!text.isEmpty()){ // Test if the text is empty
if(text.matches("[0-9]+")){ // Test if it only contains numbers, using REGEX
amount = Float.valueOf(text); // Only then parse to float.
// Switch and rest of the stuff
} else {
Toast.makeText(getApplicationContext(), "Use only numbers from 0 to 9.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "The field is empty",
Toast.LENGTH_LONG).show();
}
The comments explain what's going on. About the leading 0 in some numbers, using "valueOf" will remove it already, and 0300 will be parsed as 300, so there's nothing to worry about.If you still want something related to it, let me know and i'll edit my answer.
I am writing an app that takes two user inputs and matches them to data stored in a database and displays the corresponding data(row) from the user inputs in a textview.
The if statement works perfectly alone if d condition is true. It however stops working if I add the else statement.
The else statement is executed if d statement is true or false
String name = Jasonobject.getString("name");
String name1 = Jasonobject.getString("name1");
String db_detail = "";
// match user input with database and display corresponding row in
// "detail" textfield
if (et.getText().toString().equalsIgnoreCase(name)
&& et1.getText().toString().equalsIgnoreCase(name1)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
} else {
Context context = getApplicationContext();
CharSequence text = "NOT AVAILABLE";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
}
The else statement cannot run if the if statement is true at any cost.
Try to clean your project and re-compile it. Also are you executing this code in an loop, if not then you should get a misplace break error.
I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
textfield2.setText(textfield2.getText().toString());
if(word == answer){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?
You can't compare strings with the == operator.
Use .equals() instead:
if(word.equals(answer)) {
//do whatever
}
Use String.equalsIgnoreCase for comparing content of both string variables.:
if(word.equalsIgnoreCase(answer)){
}
Use:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(answer.contentEquals(word)){
// Do something if equals
}
else{
// Do something if not equals
}
I think the best way to do this is using TextUtils:
if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
//do something
}
instead of
if(word.contentEquals(answer)){
}
Use
if(word.equals(answer))
as we cant compare strings with Equal to (==) operator
Try This::
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(word.equals(answer)){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
Not sure if I've missed something really obvious. I know for sure that my String is as follows:
1This is a test message
I'm trying to detect whether the first character is '1', so here's some of my code:
//This outputs '1'
Toast noCmd = Toast.makeText(Play.this, decodedMessage.substring(0,1), Toast.LENGTH_SHORT);
noCmd.show();
if (decodedMessage.charAt(0) == 1) {
noCmd = Toast.makeText(Play.this, "This should show up", Toast.LENGTH_SHORT);
noCmd.show();
noCmd = Toast.makeText(Play.this, finalMessage + " from " + sender, Toast.LENGTH_SHORT);
noCmd.show();
}
if (decodedMessage.substring(0,1) == "1") {
noCmd = Toast.makeText(Play.this, "This should show up", Toast.LENGTH_SHORT);
noCmd.show();
noCmd = Toast.makeText(Play.this, finalMessage + " from " + sender, Toast.LENGTH_SHORT);
noCmd.show();
}
As you can see, I'm trying two methods to get the toasts inside the if statement to show up. Weirdly, when the code is run, only the top (unconditional) toast displays.
Any ideas?
For the first one, the char is '1'. What's currently happening in your code is that because you're comparing a char with an integer, the char is being converted to an int using its character code. For a 1, that comes out as 49, which is not equal to the integer 1. You need to compare the char you're retrieving from the String with the char representing a digit "1", and that means you need to write it as '1'.
For the second one, you need to use .equals() to test for String equality, rather than ==. If you take two String objects s and t that have the same content, then you still will find that s==t will come out as false, unless they happen to be pointing at the same bit of memory (i.e., they're the same instance). To check whether they have the same content, you check
s.equals(t)
rather than
s==t
So, in summary, make the first one
if (decodedMessage.charAt(0) == '1') {
//toast stuff
}
and the second one
if ("1".equals(decodedMessage.substring(0,1))) {
//toast stuff
}
The reason, by the way, for not writing
if (decodedMessage.substring(0,1).equals("1")) {
//toast stuff
}
instead is that if the String on which you call .equals() is null then you'll end up with a NullPointerException, which usually you want to avoid. Actually in this case it would be fine, because the substring() call won't return null, but in the general case if you want to test whether s and "something" are equal then you use
"something".equals(s)
rather than
s.equals("something")
just in case s is null.
1 is an integer with value 1. If you want the ASCII 1, use '1' in single quotes which has the integer value of 49.
For comparing strings, use equals() and not ==. See How do I compare strings in Java?
To compare strings you need to use equals method:
if("1".equals(decodedMessage.charAt(0))){
}
I'm trying to get values out of edittext boxes and on the click of a button, I want to compare if the text inside the edittext box matches a certain value. If it does, a new intent should be called. If it doesn't it should show an error. Here is my code after the button is clicked...
if(v.getId() == R.id.button1){
id = et1.getText().toString();
Toast toast = Toast.makeText(this, "Value of id is: " + id, Toast.LENGTH_SHORT);
toast.show();
if(id == "abc"){
Intent i= new Intent(Slogin.this, Sales.class);
startActivity(i);
}else{
Toast toast = Toast.makeText(this, "Wrong id pass", Toast.LENGTH_SHORT);
toast.show();
}
Now the problem is that even when I enter "abc" (without the double commas), it still shows me the error "Wrong id pass". While the Toast clearly shows that I have entered abd and the string id now holds the value "abc". Help required...
Try this.. if id is int use like this id == 5. but id is String you should use id.equals("abc")
if(id.equals("abc")){ //Correction is here
Intent i= new Intent(Slogin.this, Sales.class);
startActivity(i);
}else{
Toast toast = Toast.makeText(this, "Wrong id pass", Toast.LENGTH_SHORT);
toast.show();
}
== always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal......
Use
if(id.equals("abc"))
instead Of
if(id == "abc")