Convert ImageView to Integer: Android Studio - java

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

Related

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

How to run Multiple case at a time in Android studio

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
.

The increment counter in method not working for java

I am developing two separate program which involve method call from each side.Program A is MyNoteCenter.java and program B is SocketServer.java. There consist of a method call in MyNoteCenter to trigger the method in the SocketServer for download the resource, so the counter in SocketServer will increment by 1. when I click the button download inside the MyNoteCenter, it will contact the SocketServer for download request and increment the counter by one if SocketServer receive valid argument but why my counter only rise one time? it will only function well for the first time I click the download button but when I click the second time, the counter still showing 1
This is some portion of my SocketServer program
public String getDownload()
{
int c = 0;
c = c + 1;
switch(software)
{
case "1" :
message = "ITune";
// counter++;
break;
case "2" :
message = "ZoneAlarm";
// counter++;
break;
case "3" :
message = "Winrar";
// counter++;
break;
case "4" :
message = "Audacity";
// counter++;
break;
}
JOptionPane.showMessageDialog(null,"Your download is\n" +message+ "\n the number of download is\n"+c);
return message;
}
This is the method in MyNoteCenter, the method will be trigger after the btn2 is click which is download button, the runCC method will contact the SocketServer method for download
public static void runCC(String software,String id,String name,String job,String country)
{
SocketServer dc = new SocketServer(software,id,name,job,country);
String ServerReplyMessage = dc.getDownload();
JOptionPane.showMessageDialog(null,"Downloading :\n" +ServerReplyMessage);
int answer = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer == JOptionPane.NO_OPTION)
{
JOptionPane.showMessageDialog(null,"Please click close button");
}
else
{
JOptionPane.showMessageDialog(null,"Please proceed");
}
http://codepad.org/ >>my full SocketServer program
You are re initializing c every time you run the method.
c should be a field defined within the class that will maintain value every time you need to increment it OR evaluate it's current value.
public class MyClass {
private int c = 0;
public String getDownload() {
c++;
switch case...
}
}

How to write code that if something happens nothing else happens afterward?

Lets say if the last level of a game is beaten then you dont show a dialog box asking if the player wants to go on to the next level, but rather to the mainmenu. SO basically if something happens the things that are supposed to happen afterward dont.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
final ImageIcon pokeballIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\pokeball5.gif");
final ImageIcon pokemoneggIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\nidoking.gif");
final ImageIcon pokemonredIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\red.gif");
String userAnswer = answertextArea.getText().trim();
if (userAnswer.equalsIgnoreCase(answers.get(questionNumber))) {
answerLabel.setText("Correct");
levelScore ++;
triviagui.totalScore ++;
} else {
answerLabel.setText("Incorrect");
}
answertextArea.setText("");
questionNumber++;
if(questionNumber == questions.size()){
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores",JOptionPane.INFORMATION_MESSAGE, pokeballIcon );
if(difficulty == 3){
JOptionPane.showMessageDialog(null, "Good job you beat the game! \n Your total score was " + triviagui.totalScore + " out of 30.", "Thanks for playing!", JOptionPane.INFORMATION_MESSAGE, pokemonredIcon);
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
int leveloptionPane = JOptionPane.showConfirmDialog(null,"Would you like to go on to the next level?" , "Next Level?", JOptionPane.YES_NO_OPTION, levelScore, pokemoneggIcon);
if(leveloptionPane == JOptionPane.YES_OPTION){
difficulty++;
triviagui.questionFrame.setVisible(false);
triviagui.questionFrame=new QuestionFrame(difficulty);
triviagui.questionFrame.setVisible(true);
}
if(leveloptionPane == JOptionPane.NO_OPTION){
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
return;
}
updateQuestionScore();
}
You simply want to do:
if(something happens) {
return;
}
If you want to jump out from method use
return;
example of something like that:
public void myMethod(){
if(mynumber==5){
doThis();
}else{
return;
}
/*
*do something else <- this wont be executed if number doesnt equal 5
*cause we are already out of method.
*/
}
If you dont want to jump out from whole method bud only form part of it for instance loop.
break;
example of that:
public void myMethod(String[] stringArr){
for(String s:stringArr){
if(s.equals("hello")){
break; //get me out of this loop now !
}else{
s+="alriight";
}
}
}
doSomethingElse();//this will be executed even if you go thru break; you are still inside method dont forget.You are just out of loop
}
There are better uses for that maybe examples aint best bud you will understand how to use it form this:).
When you use break or return.In eclipse for instance you will be shown Where you actually exit. it will highlight "}"
There are several ways to do this:
You can return from a method.
You can break to exit a loop or continue to start the next iteration of the loop.
You can use an 'else' to only execute other code if the first section did not execute.
You can set a boolean flag variable and then check for that elsewhere in your code.
Depending on what you are trying to do each of these is sometimes the best way, sometimes not the best way.

OnClickListener and Toast not cooperating

I've been working on this program for an Android app assignment, and though Eclipse has no problems with the code, my phone can't seem to run it. I am a novice in Android programming, so please bear with me.
This Android app is a simple "Guess My Number" game in a blank activity. The user is to guess from 1-100, enter their answer inside a EditText view, and submit it with a push of a button. The design is fine, but getting it to work with OnClickListener is a hassle. The app crashes on my GS3 as soon as I press the button. The most troubling part is getting the button to act and give outputs in the form of Toast.
Attached is the code from MainActivity.java.
I managed to pick up different snippets of code through StackOverflow as well as a bit of Java that I knew. The result is imperfect; it was worth trying though.
You may see my complete project here. Thank you for your time, and I appreciate whatever help I can get.
package com.lookjohn.guessnumber;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Random random;
Button button;
EditText text;
int input;
int MIN = 1, MAX = 100;
int comp;
int guesses;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
button = (Button)findViewById(R.id.button1);
text = (EditText)findViewById(R.id.editText1);
comp = random.nextInt(MAX - MIN + 1) + MIN;
guesses = 0;
button.setOnClickListener(myhandler1);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
String value = text.getText().toString(); // Get value from input from editTextView
input = Integer.parseInt(value); // Turn string into integer
do{
guesses++;
if(input > comp)
Toast.makeText(MainActivity.this,
"Number is too big.",
Toast.LENGTH_SHORT).show();
else if (input < comp)
Toast.makeText(MainActivity.this,
"Number is too small.",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this,
"Good job! That was correct." +
"You made " + guesses + " guesses.",
Toast.LENGTH_SHORT).show();
} while(input != comp);
}
};
Edit: I've found a couple other issues in your code. First, your EditText's input type is phone. It should be number. Also, a user can submit a blank edit text, which will cause the app to crash when you call parseInt. I've taken care of that in some changes to your code below.
The problem is in your loop. After submit is pressed, you are entering an infinite loop. I think you are expecting the user to be able to submit multiple guesses. But if the user has entered "3" and your computed value is "10", all your loop is doing is determining that 3 != 10 over and over and over again. This causes the UI to freeze.
Removing your while loop will allow the Toast to show:
public void onClick(View v) {
// If you want to implement a max number of guesses, detect the
// number of guesses and return from the method.
if (guesses > 5) {
Toast.makeText(MainActivity.this, "Out of guesses!", Toast.LENGTH_SHORT);
return;
}
String value = text.getText().toString(); // Get value from input from editTextView
// If the user submits an empty EditText, return so we don't crash when parsing int
if (value.isEmpty()) {
Toast.makeText(MainActivity.this, "You must enter a guess!", Toast.LENGTH_SHORT);
return;
}
input = Integer.parseInt(value); // Turn string into integer
guesses++;
if(input > comp)
Toast.makeText(MainActivity.this,
"Number is too big.",
Toast.LENGTH_SHORT).show();
else if (input < comp)
Toast.makeText(MainActivity.this,
"Number is too small.",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this,
"Good job! That was correct." +
"You made " + guesses + " guesses.",
Toast.LENGTH_SHORT).show();
}
And in your main.xml, change your inputType from phone to number:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/button1"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number" />
You have made the infinite loop in your click listener for the guess variable which is always getting incremented and doesn't stops.
Just remove the do{...}while loop and then try out. As there doesn't seems to require any use of it.
if(input > comp)
Toast.makeText(MainActivity.this,
"Number is too big.",
Toast.LENGTH_SHORT).show();
else if (input < comp)
Toast.makeText(MainActivity.this,
"Number is too small.",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this,
"Good job! That was correct." +
"You made " + guesses + " guesses.",
Toast.LENGTH_SHORT).show();

Categories