if statment not working properly in android - java

hello guys im newbie in android i want just to change the text view text if the caculate value between 18 or 25 i used if statment but there is no results
any idea sometimes if i removed one of the >its worked but only for biggest value
public class GB extends ActionBarActivity {
ImageView im1;
EditText mEditText1,mEditText2;
TextView mTextView,m5;
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_GB);
im1 = (ImageView)findViewById(R.id.imageView1);
mEditText1 = (EditText)findViewById(R.id.editText1);
mEditText2 = (EditText)findViewById(R.id.editText2);
mTextView = (TextView)findViewById(R.id.textView4);
m5 = (TextView)findViewById(R.id.textView5);
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
}
String word2 = mEditText2.getText().toString();
String word = mEditText1.getText().toString();
if (word.trim().equals("")){
mEditText1.setError("Insert Hight");
}
else if (word2.trim().equals("")){
mEditText2.setError("Insert Wight");
} else{
calculate();
}
}
});
}
public void calculate(){
Double value1 = Double.parseDouble(mEditText1.getText().toString());
Double value2 = Double.parseDouble(mEditText2.getText().toString());
Double calculatedValue = value1/(value2*value2)*10000;
calculatedValue = Math.round(calculatedValue*10)/10.0d;
mTextView.setText(calculatedValue.toString());
if (mTextView.getText().toString().trim().length() <10 && mTextView.getText().toString().trim().length() >18) {
im1.setBackgroundResource(R.drawable.s1);
m5.setText("low");
} else if (mTextView.getText().toString().trim().length() <18 && mTextView.getText().toString().trim().length() >25) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("Best");
} else if (mTextView.getText().toString().trim().length() <25 && mTextView.getText().toString().trim().length() >100) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("over");
}
}
}

An integer value cannot be smaller than 18 and bigger than 25 at the same time.
Instead of
if (mTextView.getText().toString().trim().length() <18 && mTextView.getText().toString().trim().length() >25)
Use this one if you want to check a value between 18 and 25.
if (mTextView.getText().toString().trim().length() > 18 && mTextView.getText().toString().trim().length() < 25)

If you want to check if a value is in an interval, you have to write it as follows:
if(myvalue > lowerbound && myvalue < upperbound )
The following code probably does what you want.
public void calculate(){
Double value1 = Double.parseDouble(mEditText1.getText().toString());
Double value2 = Double.parseDouble(mEditText2.getText().toString());
Double calculatedValue = value1/(value2*value2)*10000;
calculatedValue = Math.round(calculatedValue*10)/10.0d;
mTextView.setText(calculatedValue.toString());
if (calculatedValue >= 10 && calculatedValue < 18) {
im1.setBackgroundResource(R.drawable.s1);
m5.setText("low");
} else if (calculatedValue >= 18 && calculatedValue < 25) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("Best");
} else if (calculatedValue >= 25 && calculatedValue < 100) {
im1.setBackgroundResource(R.drawable.s3);
m5.setText("over");
}
}

Your switch statement here is useless, You have already set click listener to button and again you are trying to check if it's the same button clicked.
It would good if you check if the value entered is numeric.
when you use if, else if and else - one and only one will be executed, which ever full fills the statement will be executed and rest of the code won't execute, say for instance have a look at the following:
if( a > b){
//show A is bigger than b;
} else if ( a == b){
// show A equals to b
} else{
// b > a
}
Here,
if (word.trim().equals("")){//if this conditions works, code won't go to test else if or else statement.
mEditText1.setError("Insert Hight");
}
else if (word2.trim().equals("")){
mEditText2.setError("Insert Wight");
} else{
calculate();
}
The way you are checking the values is wrong, the statement will be always false, as 1. you are testing if the value if < 10 and at the same time you are test if the value is > 18, one of which be false for sure.
if(mTextView.getText().toString().trim().length() <10 && mTextView.getText().toString().trim().length() >18)

Related

How to make Toast pop up if EditText field is empty or the inputted value is equal to 0?

First of all, I'm new to Android Studio. I'm currently trying to make a BMI calculator app where the user has to enter their weight and height and select the unit of measurement used for both. A Toast message (R.string.toastError) should pop up upon clicking a button if: (1-2) the EditText fields for weight and height are empty and (3) if the value of HeightInput is less than or equal to zero; else, the calculation should proceed.
The whole math part worked fine when I tested it, but when I left the fields blank, the app just crashes. The Toast pops up though when HeightInput = 0, but not when the EditText field for Weight is left empty at the same time. I think it's the way I wrote the 'if' statement that's giving me a problem.
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
Here's the whole code for reference:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// weight units spinner
final Spinner spinWeightUnit = (Spinner) findViewById(R.id.spinnerWeightUnit);
spinWeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> WeightList = ArrayAdapter.createFromResource(this, R.array.WeightUnits, android.R.layout.simple_spinner_item);
WeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinWeightUnit.setAdapter(WeightList);
// height units spinner
final Spinner spinHeightUnit = (Spinner) findViewById(R.id.spinnerHeightUnit);
spinHeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> HeightList = ArrayAdapter.createFromResource(this, R.array.HeightUnits, android.R.layout.simple_spinner_item);
HeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinHeightUnit.setAdapter(HeightList);
// calculate button
Button buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
// weight conversion constant
if (finalWeightUnit.equals("kilograms")) {
constantWeight = 1.00;
} else {
constantWeight = 1 / 2.204623;
}
// height conversion constant
switch (finalHeightUnit) {
case "inches":
constantHeight = 0.0254;
break;
case "centimeters":
constantHeight = 0.01;
break;
case "feet":
constantHeight = 1 / 3.2808;
break;
default:
constantHeight = 1.00;
break;
}
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'd appreciate any help! Thanks!
Try below in if statement
if (editTextWeightInput.getText().toString().trim().isEmpty() || editTextHeightInput.getText().toString().trim().isEmpty() || HeightInput <= 0)
When you leave an EditText Empty the getString() function returns a null value. First you need to check for null in the if condition.
if (editTextWeightInput.getText() == null || editTextWeightInput.getText().toString().length() == 0 || HeightInput <= 0)
You need to validate your declaration code also.
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
if(TextUtil.isEmpty(editTextWeightInput.getText().toString())||TextUtil.isEmpty(editTextHeightInput.getText().toString())){
Toast.makeText(getApplicationContext(), R.string.toastError,
Toast.LENGTH_SHORT).show();
}else{
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
}

Could not understand, why the logic in updateQuestionTrue/ updateQuestionFalse is making an error

Working on a one tutorial. Decided to implement the method logic to decrement or increment the array index. Somehow, it is still going outside the size of my array. Why is it happening?
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getApplicationContext(),"You are right!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
mTextView = (TextView) findViewById(R.id.question_text_view);
mTextView.setText(mQuestionBank[mIndex].getQuestionId());
updateQuestionTrue();
}
});
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getApplicationContext(),"Nope...", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
mTextView = (TextView) findViewById(R.id.question_text_view);
mTextView.setText(mQuestionBank[mIndex].getQuestionId());
updateQuestionFalse();
}
});
Here is the wrong logic method. Could you explain me, why it is going outside the size of my array?
private void updateQuestionTrue() {
mIndex++;
if(mIndex == mQuestionBank.length) {
mIndex = 0;
}
}
private int updateQuestionFalse() {
mIndex--;
if(mIndex == 0) {
mQuestionBank[0].getQuestionId();
}
return 0;
}
You should ensure that your index will always be in a valid range based on the length of your array. You can try the following
private void updateQuestionTrue() {
if(mIndex + 1 >= mQuestionBank.length) {
mIndex = 0;
}
else
mIndex++;
}
private int updateQuestionFalse() {
if(mIndex - 1 <= 0) {
//mIndex = mQuestionBank.length - 1; //too loop back around
mIndex = 0; //or to keep the index at 0 once you are as far back as possible
}
else
mIndex--;
return mIndex;
}
You can also use my personal favorite, ternary operator
private void updateQuestionTrue() {
mIndex = mIndex + 1 >= mQuestionBank.length ? 0 : ++mIndex;
}
private int updateQuestionFalse() {
return (mIndex = mIndex - 1 <= 0 ? 0 : --mIndex);
}
Just as updateQuestionTrue() sets mIndex to 0 when it would otherwise equal mQuestionBank.length, updateQuestionFalse() should set mIndex to mQuestionBank.length - 1 when it would otherwise be less than 0. In this way, it will loop to the end when you go back before the start, just as it loops to the start when you go off the end.
I'm not sure what mQuestionBank[0].getQuestionId(); does in your code, though.

How to set click limit of clicking a button? click limit is equal to score over 5

How can I set a limit of clicking a button? The number of click is equal to score % 5.Example score is equal to 15 the number of click limit is equal to 3 how can I do that? my codes is not working
int score = 0;
int help = score % 5;
if (score == help) {
helpbtn.setEnabled(false);
} else {
helpbtn.setEnabled(true);
}
I put it inside of
public void onClick(View v) { }
If in the example limit is 3, then :
if(help>0)
{
//logic;
help--;
}
you can add it in else block.
I think I understand what you need now. I've made some assumptions. I added a separate button to submit answers and I added a boolean that is always true for now. I did manage to use modulo in this version though. Hope this helps.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private int score = 0;
private int help = 0;
private boolean answerCorrect = true; // dummy set always true for now
private Button answerButton = null;
private Button hlpbtn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answerButton = (Button)findViewById(R.id.button_answer);
answerButton.setOnClickListener(this);
hlpbtn = (Button)findViewById(R.id.button_help);
hlpbtn.setOnClickListener(this);
hlpbtn.setEnabled(false);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.button_answer) {
if(answerCorrect) {
if((++score % 5) == 0) {
++help;
}
if((help > 0) && !hlpbtn.isEnabled()) {
hlpbtn.setEnabled(true);
}
}
Log.d("Quiz", "score = " + score + ", help = " + help);
} else if(view.getId() == R.id.button_help) {
if(--help <= 0) {
hlpbtn.setEnabled(false);
Log.d("Quiz", "help button disabled");
}
Log.d("Quiz", "help pressed, " + help + " remaining");
}
}
}
It sounds like you want 15 / 5 instead of 15 % 5.
15 / 5 == 3, whereas 15 % 5 == 0.
15/5 =3. Try this, this will help you to click a button 3 times.
%it gives remainder. Ie --->15%5=0

How to set textview as method output in andrioid?

I have just started to use android studio recently and currently I am working on a Roman Numeral Translator app. The app's interface looks like this: Application interface
The user will use the keypad to input a integer which will show up on the TextView shown above. When they hit the convert button it will take the integer they have entered and convert it (the program will be able to catch the input if contains a string or character). Then the app will reset the TextView to the result after the user hits the "convert" button.
Currently, my main activity contains the onClickListeners for the buttons and a separate translator method for the translations. My problem is with the "convert" button I'm not sure how to get the input from the translator method and set it as TextView when it finishes converting. Here is the sample of my code:
"Convert" button listener- `
convert.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
TextView numeralInput = (TextView) findViewById(R.id.textView);
String intValue = numeralInput.getText().toString();
try{
int integer = Integer.parseInt(intValue);
if (integer > 0 && integer <= 4999){
translator(integer);
}else{
numeralInput.setText("Please enter an integer between 0 and 4,999.");
}
}catch(NumberFormatException e){
numeralInput.setText("Invalid input try again.");
}
}
}
);
`
Translator Method- `
public static void translator(int integer) {
LinkedList<String> stack = new LinkedList<String>();
// if (integer > 0 && integer <= 4999) {
//ArrayList<Integer> placement = new ArrayList<Integer>();
int place = (int) Math.log10(integer);
for (int i = 0; i <= place; i++) {
//while(integer > 0){
//System.out.println(integer);
int placeOfValue = integer % 10;
//stack.push(placeOfValue);
//System.out.print(stack);
//System.out.print(placeOfValue +":" + i);
String placement = "";
switch (i) {
case 0:
placement = ones(placeOfValue);
break;
case 1:
placement = tens(placeOfValue);
break;
case 2:
placement = hundreds(placeOfValue);
break;
case 3:
placement = thousands(placeOfValue);
break;
default:
break;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
stack.push(placement);
}
integer = integer / 10;
//System.out.print(placement);
// System.out.println(placement.size());
//}
// for(int j = 0; j < placement.size(); j++){
// double tenthPower = Math.floor(Math.log10(placement.get(j)));
// double place = Math.pow(10, tenthPower);
// System.out.println(place);
//
// }
// }
while (!stack.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
System.out.print(stack.pop());
}
}
// } else {
// System.out.println("Please enter an integer between 0 and 4,999.");
// }
}
}
`
The other methods inside translator is like a library for the roman numerals each containing a numeral for each of the place values as shown below.
Thousands method- `
public static String thousands(int integer) {
String thouValue = "";
switch (integer) {
case 1:
thouValue = "M";
//System.out.print("M");
break;
case 2:
thouValue = "MM";
//System.out.print("MM");
break;
case 3:
thouValue = "MMM";
//System.out.print("MMM");
break;
case 4:
thouValue = "MMMM";
//System.out.print("MMMM");
break;
default:
thouValue = "";
break;
}
return thouValue;
}
`
Make your translator() method return a string which contains the final output.
So before the while statement in that method, declare a string such as
String result = null; and in the loop append the popped values to this variable like, result += stack.pop().
Now, the place where you call the translator(integer) method, do numeralInput.setText(translator(integer)) instead of translator(integer)
You need to make your TextView a class member and initialise it in your oncreate bundle, so that you can access the textview elsewhere in the activity.
TextView numeralInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
numeralInput = (TextView) findViewById(R.id.textView);
convert.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
String intValue = numeralInput.getText().toString();
try{
int integer = Integer.parseInt(intValue);
if (integer > 0 && integer <= 4999){
translator(integer);
}else{
numeralInput.setText("Please enter an integer between 0 and 4,999.");
}
}catch(NumberFormatException e){
numeralInput.setText("Invalid input try again.");
}
}
}
);

Why does it call method 'isCorrect' multiple times (onClick) if I hit the button only once?

I made a simple quiz game for android, right now there's only 10 questions, and 40 answers. (4 answers for each question)
Sometimes when I hit a button it gives me more than one correct answer at a time, also it might even do it when answer's not correct.
Any idea what's wrong in this code? Cause Im not calling the isCorrect boolean method multiple times (in one click).
Code:
public class ETBetaActivity extends Activity implements View.OnClickListener {
Button answer_1,
answer_2,answer_3,
answer_4,main;
TextView q_textview,
tip;
private String a1,a2,a3,a4 = "";
private int i1 = 0;
public static int correct = 0;
private boolean alive = true;
MediaPlayer button_click;
private String[] questions =
{"Q1",
"Q2",
"Q3",
"Q4",
"Q5", //5
"Q6",
"Q7",
"Q8",
"Q9",
"Q10" //10
};
public static int question_amount = 10;
private String[] answers_correct =
{"Correct answer - 1",
"Correct answer - 2",
"Correct answer - 3",
"Correct answer - 4",
"Correct answer - 5",
"Correct answer - 6",
"Correct answer - 7",
"Correct answer - 8",
"Correct answer - 9",
"Correct answer - 10"
};
private String[][] answers_wrong =
{ {"Q1-1", "Q1-2" , "Q1-3"},
{"Q2-1", "Q2-2" , "Q2-3"},
{"Q3-1", "Q3-2" , "Q3-3"},
{"Q4-1", "Q4-2" , "Q4-3"},
{"Q5-1", "Q5-2" , "Q5-3"},
{"Q6-1", "Q6-2" , "Q6-3"},
{"Q7-1", "Q7-2" , "Q7-3"},
{"Q8-1", "Q8-2" , "Q8-3"},
{"Q9-1", "Q9-2" , "Q9-3"},
{"Q10-1", "Q10-2" , "Q10-3"}
};
List<String> question_list = new ArrayList<String>();
List<String> answer_list_correct = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getData();
Game(i1);
}
#Override
public void onClick(View view) {
if (alive == false) {
// startActivity(new Intent("com.aleksei.etb.END"));
return;
}
button_click = MediaPlayer.create(this, R.raw.button_click);
button_click.start();
switch(view.getId()){
case R.id.button5: //main
break;
case R.id.button1: //answer_1
if(isCorrect(1))
correct++;
break;
case R.id.button2: //answer_2
if(isCorrect(2))
correct++;
break;
case R.id.button3: //answer_3
if(isCorrect(3))
correct++;
break;
case R.id.button4: //answer_3
if(isCorrect(4))
correct++;
break;
default:
break;
}
Game(i1);
tip.setText("Correct answers: "+correct);
}
public static int getResults(){
int value = (int) Math.floor((correct*5)/question_amount);
if(value <= 0)
return 1;
else
return value;
}
private boolean isCorrect(int button){
for (int i = 0; i < answers_correct.length; i++){
if(button == 1 && a1 == answers_correct[i]
|| button == 2 && a2 == answers_correct[i]
|| button == 3 && a3 == answers_correct[i]
|| button == 4 && a4 == answers_correct[i])
return true;
}
return false;
}
private void Game(int q){
if(i1 == question_amount) { //no more questions
startActivity(new Intent("com.aleksei.etb.END"));
alive = false;
return;
}
try {
main.setText("Dunno");
String answer_list[] = {
answers_correct[q], answers_wrong[q][0] , answers_wrong[q][1] , answers_wrong[q][2]
};
Collections.shuffle(Arrays.asList(answer_list));
answer_1.setText(answer_list[0]);
answer_2.setText(answer_list[1]);
answer_3.setText(answer_list[2]);
answer_4.setText(answer_list[3]);
a1 = answer_list[0];
a2 = answer_list[1];
a3 = answer_list[2];
a4 = answer_list[3];
q_textview.setText(questions[q]);
} catch (Exception ex){}
i1++;
}
private void getData(){
//Getting the data
main = (Button) findViewById(R.id.button5);
answer_1 = (Button) findViewById(R.id.button1);
answer_2 = (Button) findViewById(R.id.button2);
answer_3 = (Button) findViewById(R.id.button3);
answer_4 = (Button) findViewById(R.id.button4);
q_textview = (TextView) findViewById(R.id.question);
tip = (TextView) findViewById(R.id.answ1);
//Making the buttons, actually work
main.setOnClickListener(this);
answer_1.setOnClickListener(this);
answer_2.setOnClickListener(this);
answer_3.setOnClickListener(this);
answer_4.setOnClickListener(this);
//Resets the text
//Note to self: Replace with another ContectView
main.setText("Begin!");
answer_4.setText("");
answer_3.setText("");
answer_2.setText("");
answer_1.setText("");
tip.setText("");
}
}
Consider the following changes and see if it improves:
private int questionNumber = -1;
private void Game(int q){
...
questionNumber = q;
q_textview.setText(questions[q]);
...
}
private boolean isCorrect(int button){
if(button == 1 && a1.equals(answers_correct[questionNumber])
|| button == 2 && a2.equals(answers_correct[questionNumber])
|| button == 3 && a3.equals(answers_correct[questionNumber])
|| button == 4 && a4.equals(answers_correct[questionNumber]))
return true;
}
return false;
}
Storing the question number as a field eliminates the for loop over all the questions.
You should always use String.equals instead of ==.

Categories