if /else statement not working in android app - android

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.

Related

Android: changing variable using if statement

This is a OnClickListener for button
name is EditText
I want it print only "hi" if nothing is entered, but "hi" + name + "!" if user inputs his/her name.
public void onClick(View view) {
if (button==view) {
String message;
if (name.getText().toString().matches("")) {
message = "hi!";
return;
}
else {
message = "hi" + name.getText().toString() + "!";
return;
}
Toast toast = Toast.makeText(this,message,Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
}
}
For some reason I got error "unreachable statement" for the line:
Toast toast =...,
And if I compile and run it, the screen will output on 2 lines instead of one, such as:
Hi
!
What did I do wrong in here?
Why do you have the return statement? You need to show the Toast and then return. Remove the return statements.

Android app crashes when no value is in edit text

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.

How to see what is returned ? (true / false )

It might sound stupid but seriously, I am looking for an error, from what I read on internet I should try to read what has been returned (in my case "cursor.moveToFirst()", true or false) but I can't find where to see this. No message in my app of course, nothing in the logcat, so where is it ?
Thanks !
you can try
boolean result = cursor.moveToFirst();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, "debug:" + result , duration).show();
it'll then pop up on your device.
or you can try
boolean result = cursor.moveToFirst();
Log.d("TESTING", "debug:" +result);
then filter the LogCat with "TESTING"

Updating a default Phone Number

I have an EditText field, which I have a default value from
strings.xml ( android:text="#string/DefaultMobileNumber").
When the user updates this (button listener), I am storing the new value in SHARED_PREFERENCES, however, the new value will not show on screen when the page is re-displayed (the default from strings.xml persisits). I am using
final EditText phoneNoText = (EditText) findViewById(R.id.InPhone);
if (mSettings.contains(PREFERENCES_PHONENO)) {
String sPhoneNoText = (mSettings.getString(PREFERENCES_PHONENO,"No Number"));
phoneNoText.setText(sPhoneNoText);
//Toast.makeText(getBaseContext(), sPhoneNoText, Toast.LENGTH_SHORT).show();
}
else
{// write default value to PREFERENCES_PHONENO
editor.putString(PREFERENCES_PHONENO, "07799060000");
editor.commit();
//Toast.makeText(getBaseContext(), "No Phone", Toast.LENGTH_SHORT).show();
};
Hopefully I've made a stupid error, but can't seem to find it!!!

Display text with if statement

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();

Categories

Resources