android apps using if else statement with multiple condition - android

Hye, I have a problem and a bit confuses to solve it… I need to create a checklist for user to answer in my android apps..it contain several questions…for example, I have 5 questions and user need to answer by choosing the options on radiobutton…So basically this checklist is to check if the user is allowed to drive a car or not..
1) Are you under influence of drugs? //RG1, rbyes1, rbno1
O Yes O No
2) Do you have driving license? //RG2, rbyes2, rbno2
O Yes O No
3) Do you have a car? //RG3, rbyes3, rbno3
O YES O No
4) Are you drunk? //RG4, rbyes4, rbno4
O Yes O No
5) Are you colour blind? //RG5, rbyes5, rbno5
O Yes O No
User need to answer
1) No
2) Yes
3) Yes
4) No
5) No
To make the user eligible to drive a car..
If user answer the opposite, system should display the reason for every opposite answer..
This is my sample code
If(RG1. getCheckedRadioButtonId() == R.id.rbno1 &&
RG2. getCheckedRadioButtonId() == R.id.rbyes2 &&
RG3. getCheckedRadioButtonId() == R.id.rbyes3 &&
RG4. getCheckedRadioButtonId() == R.id.rbno4 &&
RG5. getCheckedRadioButtonId() == R.id.rbno5)
{
Toast.makeText(getApplicationContext(),”Congratz, you can drive”, Toast.LENGTH_LONG).show();
}
Above code is user answers for the eligible one..what if the user answer like this
1) No
2) No
3) Yes
4) Yes
5) No
So, system should display
{
Toast.makeText(getApplicationContext(),”Sorry, you are not allow to drive because you have\n“+
“2) No driving license\n” +
“4) influenced of alcohol\n”, Toast.LENGTH_LONG).show();
}
This is a piece of my idea for what I can do..Do I need to create every possibilities???.. because for the actual one, I got more than 10 questions… So, that’s means there will have many condition.. and I also confuse how to write it in code because of too many condition..hopefully you guys understand what I means and can help me…thank you..!

You do not need to check for every possibility. You check every answer only once and keep track of the error messages, e.g.:
boolean canDrive = true;
ArrayList<String> errorMessages = new ArrayList<String>();
if(RG1.getCheckedRadioButtonId() == R.id.rbno1) {
canDrive = canDrive && true;
} else {
canDrive = false;
errorMessages.add("Influenced of drugs");
}
if(RG2.getCheckedRadioButtonId() == R.id.rbyes2) {
canDrive = canDrive && true;
} else {
canDrive = false;
errorMessages.add("No driving license");
}
// Check the rest of your answers
At the end of your conditions you will have the variable canDrive reflects the result of the user answers and you will have all the error messages in errorMessages list which you can loop through and display appropriately.
Try to make your code more generic, consider using Array of your CheckedRadioButtons and you can store the error message for each question using checkBox.setTag()

Solution 1:
In my opinion you have to create on Database for storing the result.
When you have to require print the error message that time you have to fire on simple select query with result yes.
then print your message
Solution 2:
You have to create arrayList and store result value if yes.
Then you have to find length of arrayList and put your condition and put message

Related

GetText compare

So i have a EditText field, which i want to, check if the age is above and under my limits.
if (Integer.parseInt(age.getText().toString()) < 18 && Integer.parseInt(age.getText().toString()) >= 0)
But also, i want to simply check if the field is empty, for what i used.
else if (age.getText().toString().isEmpty())
Unluckly this one is not working, i think it sort of get in to conflict with the first one or something, because i tried with just one condition of both, and it works..
I also tried to store in String variable the method to check isEmpty(), and also in int one, to do the age comparation, but it still not working.
Thanks in advance.
The code should be:
if (age.getText().toString().trim().isEmpty()){
//The EditText field is empty
}else{
try{
if (Integer.parseInt(age.getText().toString().trim()) < 18 && Integer.parseInt(age.getText().toString().trim()) >= 0){
//Your code here
}else{
//Input value is over 18 or under 0
}
}catch(Exception ex){
//There was an error parsing the input (if your user writes letters, parseInt fails)
}
}

Making a calculator but no way to retrieve functions

An easy way to make an android calculator would be to have 3 separate edit text boxes and have the user in put a number, a function, and then another number like 3 + 3. This would make it easier for the app dev to store the number(s) and function(s) and perform a calculation.
Now... my calculator app has the ability to out put all the input real-time, the down side is that when I retrieve what's in the input box, i retrieve it as string (to make sure i include all the functions input-ed). I know how to retrieve numbers (by using int parse) but how do I retrieve the functions such as + - / * ? (They're the main bit!! :O). Any help would me much appreciated thanks :)
Try to use a switch that analyze and identify the correct operation. Something like this:
(I suppose the content of function EditText in a string named functionSign
...
switch(functionSign)
{
case "+": return op1+op2;
case "-": return op1-op2;
...
EDIT 2:
I suppose that user can put only the functions simbols + - / * and the operations are organized in a method:
public double calculate()
{
String operations= inputEditText.getText().toString();
StringTokenizer st= new StringTokenizer(operations);
//to calculate in input must have at last one operation and two operands
//the first token must be a number (the operation scheme is (number)(function)(numeber)...)
double result=Double.parseDouble(st.nextToken());
while(st.hasMoreTokens())
{
String s=st.nextToken();
if(s.equals("+"))
result += Double.parseDouble(st.nextToken());
else if(s.equals("-"))
result -= Double.parseDouble(st.nextToken());
else if(s.equals("*"))
result *= Double.parseDouble(st.nextToken());
else if(s.equals("/"))
result /= Double.parseDouble(st.nextToken());
else
throw new Exception();
}
return result;
}
This code is a really simple example, you must be sure that the user don't try to calculate something incomplete like:
3 + 3 -
/ 3 * 5
and similar. What the user should be able to do is your decision
You can get the operator as a string and use if statements to determine what to do:
String operator=operatorEditText.getText().toString();
if (operator.equals("+")){
//addition code here
}
else if (operator.equals("-")){
//subtraction code here
}
...

Else if loop doesn't validate variable from statement

I am having a problem while looping through one of my loop constructions.
I get Question instances out of my database and one of the fields of the instance is Attempts. I pulled my database from my device and inspected it and all fields of the column attempts are filled with ints greater than 0.
int initialAttempts = 0;
initialAttempts = c.getInt(6);
q.setAttempts(initialAttempts);
and in my custom array adapter:
if (mView != null) {
int attempts = getItem(position).getAttempts();
int correctAnswer = getItem(position).getAnswerCorrect();
triangle.setVisibility(View.INVISIBLE);
if(correctAnswer == 1) {
triangle.setVisibility(View.VISIBLE);
}
else if (correctAnswer != 1 && attempts > 0) {
triangle.setVisibility(View.VISIBLE);
triangle.setImageResource(R.drawable.trianglered);
}
So the problem is it never shows trianglered. If I drop the && attempts > 0, it does show the trianglered, so I assume the error is in there. The strange thing is if I initialize attempts as 1 before the getItem(position).getAttempts, it still shows no trianglereds.
Any ideas where this goes wrong?
getItem(position).getAttempts() method returns 0. There are no other variants. Why it returns 0 is the question to you. Prefer debugging instead of asking such questions.
PS. No need to check for correctAnswer != 1 in else if statement. The opposite statement has already been checked in if and it was false.

android number format exception

I get the following exception
java.lang.NumberFormatException: Invalid int: ""
It is happening when you try to store a value into shared preferences whilst nothing has been inserted into the input field. This is because i am parsing the input as an int (as i need to do a subtraction with the figure)
This isn't much of a problem as the app will work however just incase someone using the app wants to be wierd and try and press the save button without entering any data I dont want it to insert.
I have tried the following:
else if (obj ==null || obj.currentWeight.contains("")||obj.targetWeight.contains("")){
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("No Data Stored");
builder.setMessage("Please insert your target weight and your current weight and click Store Weight")
.setPositiveButton("OK", null).show();
From what i could make out if i kept the above statement as
else if (obj ==null){
then if a null is inserted the dialog would open and display a message.
i get the number format exception.
any help would be appreciated
Generally speaking, exception processing is a good approach for this kind of undesired behavior :
if( obj != null && obj.getTargetWeight() != null ) {
try {
int i = Integer.parseInt( obj.getTargetWeight() );
//do something if target weight is a number
} catch( NumberFormatException ex ) {
//do something if target weight was not a number.
}
}
---edited to precise exception type

Compare two things doesn't work

I have a strange problem in my android app. I must compare two string which are equals. I tried this :
if (raspunsdata.equals(rok)) {
System.out.println("changed ");
} else
System.out.println("no change");
}
but I get always "no change". Before this I have System.out.println for both strings, and both of them have the same value.
I tried also (raspunsdata==rok) and raspunsdata.contentEquals(rok) but I have the same problem. Why? I cant understand this.,...please help...
You might have unwanted white spaces. Might need to use the trim function just to make sure.
if (raspunsdata.trim.equals(rok.trim())) {
System.out.println("changed ");
} else
System.out.println("no change");
}
Btw equals is the correct way to check whether the values are the same.
.equals - compares the values of both objects. If you have 2 Strings with the same characters sets .equals will return true;
== - compares if two objects references are equal.
For example:
String a = "lol";
String b = a;
a == b - will be true.
Try reading: http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml

Categories

Resources