How to run Multiple case at a time in Android studio - java

I develop a program in android studio Where we check the number is odd or even. Everything works fine but I stuck in empty field case, I am unable to perform how to check the edit field is empty or not.
et_number = findViewById (R.id.et_number);
b_go = findViewById (R.id.b_go);
tv_show = findViewById (R.id.tv_show);
b_go.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View v) {
int number = Integer.parseInt (et_number.getText().toString ());
number = number %2;
String city = et_number.getText().toString();
if (number == 0|| city.isEmpty()){
tv_show.setText ("EVEN");
et_number.getText().clear();
Toast.makeText (MainActivity.this, "empty", Toast.LENGTH_SHORT).show ();
}
else {
tv_show.setText ("ODD");
et_number.getText().clear();
}
}
});

Add if condition at first line of on click listener like this
If( ! et_number.getTex().toString().equals(""))
And all your code inside this condition
.

Related

Convert ImageView to Integer: Android Studio

I'm trying to take the target (initiated as ImageView) id and put the integer id into a switch case to look at the adjacent Views and compare their drawables to determine if that player wins or if the game continues. I have the buttonPressed variable initiated as an Integer and used the parseInt() to get the int value of target.
public void compareButton(int buttonPressed){
//int count = 0;
ImageView adjacent;
ImageView adjacentB;
switch (buttonPressed){
case R.id.imageButtonA: //this is where adjacent buttons are identified and compared
adjacent = findViewById(R.id.imageButtonB);
adjacentB = findViewById(R.id.imageButtonC);
if (target.getDrawable() == adjacent.getDrawable() && target.getDrawable() == adjacentB.getDrawable()) {
Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonE.getDrawable() & target.getDrawable() == R.id.imageButtonI.getDrawable()) {
//Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonD.getDrawable() & target.getDrawable() == R.id.imageButtonG.getDrawable()) {
//Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
}
break;
case R.id.imageButtonB:
break;
I am not filling every case for debugging purposes.
The issue I am having is when I run the emulator I get an error that says
Caused by: java.lang.NumberFormatException: For input string: "androidx.appcompat.widget.AppCompatImageButton{517eade VFED..C.. ...P..ID 45,381-304,628 #7f070072 app:id/imageButtonA}"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.connect3.MainActivity.switchColor(MainActivity.java:75)
Here is the code for the OnClickListener:
public void switchColor(View view) {
//Button pressed, depending on user, switch's to that users color; identify adjacent button ID's; toast player control switch
if (player == 1) {
source = findViewById(R.id.yellow);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonPressed = Integer.parseInt(target.toString());
compareButton(buttonPressed);
player++;
Toast.makeText(MainActivity.this, "Player 2's Turn!", Toast.LENGTH_SHORT).show();
} else {
source = findViewById(R.id.red);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonPressed = Integer.parseInt(String.valueOf(target));
compareButton(buttonPressed);
player--;
Toast.makeText(MainActivity.this, "Player 1's Turn!", Toast.LENGTH_SHORT).show();
}
Not entirely sure what is going on at this point because I thought I did everything correct but clearly something was missed. Any help would be appreciated.
change :
buttonPressed = Integer.parseInt(String.valueOf(target));
To :
buttonPressed = target.getId();
Explanation : your error says NumberFormatException means you are trying to get int value from String which is not possible to Parse or in simple your string doesn't contain proper int value and also you are passing (androidx.appcompat.widget...) as string while you have to pass button I'd

Checking which button user pressed and checking the button text

I am a noob in Java and programing and I am making an app where the user is trying to guess a city based on a picture. The user sees a picture of the city and has three buttons under the picture with different answers in them. The pictures are randomized from an array and the buttons text changes so that atleast one of the buttons has the correct answer. I want a TextView with "correct" to show if user is correct and one with "incorrect" to show if user is wrong. The text is showing up when pressing any button and not when the button with the correct text is pressed. So this is what I have tried and am stuck on. And yes I know I have many mistakes in my code, such as names of methods and so. I will change these later.
I have three booleans that are set to false, they are representing which button is pressed. You will understand more later.
Boolean test1 = false;
Boolean test2 = false;
Boolean test3 = false;
In main i have three buttons and they all call on the checkanswer function. Also they all turn their own boolean to true there, which u will se why soon. Example of one of the buttons.
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test1 = true;
checkanswer();
}
});
So here is the checkanswer function
public void checkanswer() {
DisplayRandomImage();
//Giving three strings random city names from the "cities" array.
Random rndBtnTxt = new Random();
String randomCity1 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity2 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity3 = cities[rndBtnTxt.nextInt(cities.length)];
//Setting the random city names to the three different buttons.
btn1.setText(randomCity1);
btn2.setText(randomCity2);
btn3.setText(randomCity3);
//takes the picked image from the "DisplayRandomImage" method.
String str = String.valueOf(pickedImg);
//Tells what to call the different pictures, they are known as numbers make sure they are given names instead.
if (pickedImg == 0)
str = "venice";
if (pickedImg == 1)
str = "new york";
//If-statement checking so that atleast one button has the correct answer.
if (randomCity1 != str || randomCity2 != str || randomCity3 != str) {
Random rndbtn = new Random();
Button x = btnArray.get(rndbtn.nextInt(btnArray.size()));
//Sets one of the three buttons so that it has the correct answer.
x.setText(str);
}
//See where the correct answer is
String buttonText1 = btn1.getText().toString();
String buttonText2 = btn2.getText().toString();
String buttonText3 = btn3.getText().toString();
//check if the button that the user pressed has the correct answer
if (test1.equals(true) && buttonText1.equals(str)){
CorrectAnswer();
test1 = false;
}
if (test2.equals(true) && buttonText2.equals(str)){
CorrectAnswer();
test2 = false;
}
if (test3.equals(true) && buttonText3.equals(str)){
CorrectAnswer();
test3 = false;
}
else
WrongAnswer();
}
I am not sure what I am doing wrong here. For example the "test1" is set to True when I press "btn1" and if "buttontext1" equals to the same as "str" does it should work. But for some reason it seems randomised which of the three buttons calls for the CorrectAnswer method. What am I doing wrong here?
Can we see CorrectAnswer? Also,
right off the bat, I noticed that instead of using test1, test2 and test3 to indicate which button was pressed, you can just pass some sort of argument into checkAnswer, like int button.
So onClick would look like this for the first button, and subsequent buttons by incrementing the 1:
public void onClick(View v) {
checkanswer(1);
}
and checkanswer would look like this:
public void checkanswer(int button) {
... (previous stuff) ...
//check if the button that the user pressed has the correct answer
if (button == 1 && buttonText1.equals(str)){
CorrectAnswer();
}
if (button == 2 && buttonText2.equals(str)){
CorrectAnswer();
}
if (button == 3 && buttonText3.equals(str)){
CorrectAnswer();
}
else
WrongAnswer();
}
So try this out.
Its pretty hard to tell where the bug is, if you only show us pieces of the full code.
Mistakes could be e.g. in CorrectAnswer()...
I would recommend binding onlick-listeners to your buttons instead of changing booleans.
Check this out here: https://developer.android.com/reference/android/widget/Button
Additionally I noticed another mistake:
randomCity1 != str || randomCity2 != str || randomCity3 != str
This will return true if at least one of the Strings does not contain the right answer
You probably want to enter the if-Statement, when there isnt already a button with the correct answer.This is what you would like to use:
randomCity1 != str && randomCity2 != str && randomCity3 != str
EDIT: Check out the answer of Barcode for another example of using onClicklisteners.
Thank you both for answering the question, i have found a way to complete this problem:
public void testingMethod(int button){
switch(button){
case 1:
if (buttonText1 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 2:
if (buttonText2 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 3:
if (buttonText3 == str)
CorrectAnswer();
else
WrongAnswer();
break;
}
}
And since you were wondering how the method CorrectAnswer looked like here it is, yes I know it's probably unnecessary having this method but I am noob after all.
public void CorrectAnswer() {
findViewById(R.id.txtIncorrect).setVisibility(View.GONE);
findViewById(R.id.txtCorrect).setVisibility(View.VISIBLE);
}

App does not respond while trying to access charsequence elements through a loop

i m trying to make a calculator which can solve long expressions like 30+55-(2+7-20)
but i m having some logical problem in my equal button... beq
i have tested that logical problem is in for loop but couldnt understand. any help is greatl appreciated. heres my code
beq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (status==1){
get=tvdisp1.getText(); //tvdisp1 represents textView top expression bar
// tvdisp2.setText(get); //tvdisp2 represents 2nd textView answer bar
if(get.charAt(0)=='x') {status=0;} //to check for syntax error
if(get.charAt(0)=='รท') {status=0;} // same
for(int i =0; i <= get.length(); i++ ) { // loop to check if the first character is digit or character.
if (Character.isDigit(get.charAt(i))) {
//is digit
}
else {
//is operator
}
}
if (cbracq_c>obracs_c){status=0;} // if number of closing brackets > opening brackets
if ( status == 0 ) { tvdisp1.setText("Syntax Error AC to reset");}
}
}
});
it is just as Jon Skeet said.
You count 1 to far -> get.length() gives u a length (for example) 5, so you have index from 0 to 4. But in your loop you are also try to access index 5 because of the "<=". Just change it to "<" and it should work

Using While Loop after button press to search a multidimensional array for a value

I am relatively new to making applications for an Android phone and there is a problem that I have been trying to solve for the past week. What I am trying to do is take in 4 variables, 3 of which is from spinners and using while loops and case statements to search through the database to send a string into a TextView box. The main problem I have is the while loops after the button press errors out the program. I have tried implementing different ways like using a runnable and thread to work through it but have not had any success. I would greatly appreciate any help. The way the array is built is a 54x7.
public void onClick(View v) {
// TODO Auto-generated method stub
while(AutoDatabase[i][0] != YearSelect){
i++;
}
while(AutoDatabase[i][1] != MakeSelect){
i++;
}
while(AutoDatabase[i][2] != ModelSelect){
i++;
if (LightsOut == "FDTS"){
Part = AutoDatabase[i][3];
} else if (LightsOut == "FPTS"){
Part = AutoDatabase[i][4];
} else if (LightsOut == "RDTS"){
Part = AutoDatabase[i][5];
} else if (LightsOut == "RPTS"){
Part = AutoDatabase[i][6];
}
PartDisplay.setText(Part);
}

Application stopped working

I am making an android app in java.. And basicaly i have a problem.. I have a button which is removing the last char in a string.. And this button will be used alot and if the user is pressing the button while the string is empty the application gets an error message and closes.. And i want to prevent this somehow..
This is current code for the onClickListener..
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
value = value.substring(0, value.length() - 1);
numbersArea.setText(value);
}
Any idea how i would do this?? Since im out of ideas after trying all yesterday night.
Before substring, make sure the length of the string is > 0.
if (!value.isEmpty()) {
value = value.substring(0, value.length() - 1);
numbersArea.setText(value);
}
If you don't do this check, at some point the string will have zero length and substring() will throw IndexOutOfBoundsException.
Make your listener like this:
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!value.equals("") && value != null) {
value = value.substring(0, value.length() - 1);
numbersArea.setText(value);
}
}
Basically, what it does is verify if the string is empty and different of null, if its not, it enters in the if statement.
Please, let me know if you have more doubts.
Thanks.

Categories