Increment an int each time Toast show something - java

I want to when the Toast shows message "Correct!", the TextView show score value on itself and for next times score be increment by 1. It works for first time that Toast show the message (TextView will show 1), but for second time and beyond does not work. Is that possible anyway?
int messageAnswer;
int score = 0;
if (condition is true) {
messageAnswer = R.string.correct_toast;
score++;
scoreText.setText(String.valueOf(score));
} else {
messageAnswer = R.string.incorrect_toast;
}
Toast.makeText(getApplicationContext(), messageAnswer, Toast.LENGTH_SHORT).show();

Everytime you enter this block of code, score is newly created and initialized with 0. You need to define it outside of this block, e.g. as an instance variable private int score = 0;.

It looks like your problem is that score is a local variable.
It is reset to 0 every time the function to check the answer and display the Toast is called.
You need to make it an instance variable, a field in whatever class this code is in, so that it retains its value between function calls.

You set score = 0 just before calling the toast, each time you call the toast. It should be initialized only once. You should move it upper in your program, outside the loop or however you come back here.

Related

Everytime I call my updateScore() method, it won't update the score?

I'm trying to update my score everytime I call the method "updateScore()" but for some reason it doesn't work.
if I win the first time, it will update it properly, then if I select a new game and win, it won't update the score, the score remains like it is.
Example
first win---> (X) Wins: 1
second win--->(X) Wins: 1 ????? it should be 2
.
CODE SOURCE
public void updateScore() {
xWinnerTimes = 0;
oWinnerTimes = 0;
winnerBoardO = findViewById(R.id.winner_o);
winnerBoardX = findViewById(R.id.winner_x);
if (winner == 1){
xWinnerTimes++;
winnerBoardX.setText("(X) Wins: " + (xWinnerTimes));
}
if (winner ==2){
oWinnerTimes++;
winnerBoardO.setText("(O) Wins: " + (oWinnerTimes));
}
Mention below code in onCreate Method
xWinnerTimes = 0;
oWinnerTimes = 0;
winnerBoardO = findViewById(R.id.winner_o);
winnerBoardX = findViewById(R.id.winner_x);
xWinnerTimes and oWinnerTimes should be global variable.
and According to me, if you update score on User Interface on a particular time then you have to call your method that is updateScore() in runOnUiThread
You should put xWinnerTimes = 0;
oWinnerTimes = 0; in global and remove it in updateScore(); Because you always reset it to 0.
This is because the initialization and incrementation both are in the same scope.
The first time it will show the correct result but next time value again get initialized by 0.
Try to make that variable global
Declare them outside from your method.

I want an image to fade out and the another to fade in when it is clicked and after that the other way around

The code below is supposed to fade two ImageViews, one needs to fade in and the other out depending on the value of counter. For some reason when I run the code I get the following log output:
I/Info: One
I/Info Counter:: 1
I/Info: One
I/Info Counter:: 1
...
It never shows:
I/Info: Two
I/Info Counter:: 0
Can someone explain why this is happening?
Here's the code:
public void fade(View view) {
int counter = 0;
ImageView bale = (ImageView) findViewById(R.id.bale);
ImageView pogba = (ImageView) findViewById(R.id.pogba);
if (counter == 0) {
bale.animate().alpha(0f).setDuration(2000);
pogba.animate().alpha(1f).setDuration(2000);
Log.i("Info", "One");
counter = 1;
} else if (counter == 1){
pogba.animate().alpha(1f).setDuration(2000);
bale.animate().alpha(0f).setDuration(2000);
Log.i("Info", "Two");
counter = 0;
}
Log.i("Info Counter: ", String.valueOf(counter));
}
You're making a logical error, there is nothing syntactically wrong with your code. The scope of counter is where you're having trouble. counter is a local variable, it only exists in the fade(...) method. Every time you call fade() you recreate counter and initialize it to 0. Meaning even though you set it to 1 in the if statement, it will be 0 the next time you call fade(). You either need to make it a class variable or use the alternating approach I describe below.
Non If Statement Alternating Approach:
You don't need an if statement, simply get the alpha of pogba and bale and then when you set their alphas use 1f - pogba.getAlpha() and 1f - bale.getAlpha() (using whichever method returns their alphas). Using this approach will alternate between 1 and 0.
So your fade(View view) method would look similar to the following:
public void fade(View view) {
ImageView bale = (ImageView) findViewById(R.id.bale);
ImageView pogba = (ImageView) findViewById(R.id.pogba);
// I'm not familiar with the method to get the alpha
// so it might not be getAlpha()
bale.animate().alpha(1f - bale.getAlpha()).setDuration(2000);
pogba.animate().alpha(1f - pogba.getAlpha()).setDuration(2000);
}
You would of course need to do the following somewhere else in your code, possibly the constructor.
bale.setAlpha(1f); // I'm not familiar with the method to set the alpha
pogba.setAlpha(0f); // it might be setAlpha(), but I'm not sure

Bukkit ScoreBoard Acting Weird

I have a score board like so :
int time = 15;
private ScoreboardManager sbManager;
private Scoreboard scoreBoard;
private Objective obj;
private Score s0;
public void init(Player player) {
sbManager = Bukkit.getScoreboardManager();
scoreBoard = sbManager.getNewScoreboard();
obj = scoreBoard.registerNewObjective("ScoreBoard", "dummy");
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
obj.setDisplayName("Test");
s0 = obj.getScore(Bukkit.getOfflinePlayer("Time = " + time));
s0.setScore(6);
player.setScoreboard(scoreBoard);
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
public void run() {
time--;
updateScoreBoard(player);
System.out.println(time);
}
},20, 20);
}
And whenever I try to update it, it just dosen't work and btw my score board is a "fancy" one, so it should look like :
Time = time 6 <- the '6' is the default minecraft score.
Here's an example of my update method:
public void updateScoreBoard(Player p){
s0 = obj.getScore(Bukkit.getOfflinePlayer("Time =" + time));
s0.setScore(6);
p.setScoreboard(scoreBoard);
}
Because you're using scoreboards in an unconventional way, things are bound to get tricky. By "fancy" I assume you mean the scoreboards which display a score's name and value right next to each other on the left side, which is done by placing the actual score value inside the name String of the score (like you have already done).
The problem with your code specifically is that you are not actually changing the value of the existing score entry (since that value is set to 6 to keep the entry in the same row of the display) but creating a new score entry every time you update the display, since score entries are identified by their name and not their score value (this is required so that different score entries can have the same value, for example a player can have a "bank balance" score with a value of 2 and an "amount of deaths" score with a value of 2).
If this weren't the case for example, your new score entry with name "Time = 14" and a score value of 6 would override the previous score entry with name "Time = 15" because of the identical score value, but this is not the case.
When I tested your code snippet, more rows (score entries) were added until the display filled to maximum capacity. I can only assume this is what you meant by your code "acting weird" since you didn't elaborate on the expected and observed results of your code.
You'll want to remove the previous score entry with the outdated value. Because the API is not intended to be used this way, one cannot simply remove a score entry from an objective (resetting the score doesn't remove the entire entry).
You'll therefore need to create a new scoreboard with a new objective etc. every time you want to update a single "fancy" score entry. This also means that all scores displayed in the scoreboard need to be kept track of independently and re-added and re-set to the new scoreboard whenever any other "fancy" score is updated.
These changes to your updateScoreboard method did the trick for me:
public void updateScoreBoard(Player p) {
scoreBoard = sbManager.getNewScoreboard();
obj = scoreBoard.registerNewObjective("ScoreBoard", "dummy");
obj.setDisplaySlot(DisplaySlot.SIDEBAR);
obj.setDisplayName("Test");
s0 = obj.getScore(Bukkit.getOfflinePlayer("Time = " + time));
s0.setScore(6);
p.setScoreboard(scoreBoard);
}
Note that this method only fixes the immediate issue of more entries being added, if you want more "fancy" and possibly even normal score entries, all of those will need to be handled respectively.
All this extra work and having meaningless numbers/values always on the right of the display seem like a large trade-off just to remove a little whitespace between a score's name and value.
Some other tips: You don't need to update the sbManager variable every time you initiate the scoreboard for a new player, the manager is always the same object, so using Bukkit.getScoreboardManager() once should suffice.

Android SharedPreferences auto incrementing technique

I wanted some feedback on this approach. My apologies if this is confusing or nonsensical. (thats probably why I'm asking because im unsure.)
My app auto assigns clientID's to a textview at first launch - is auto set to 100. To do this from that point forward I store an int value to sharedpreferences. At Oncreate I run a check against this specific ID in the sharedpreferences and later it either increments or assigns back to 100. The challenge was that sharedpreferences (that I know of) can only take a string value i.e. (editor.putString("CLIENTID", ID);) or editor.putInt("ID", c);
I wanted to avoid using a database for this portion to minimize overhead (could be wrong) There are validations in place that prevent this from being incremented unless certain conditions are met.
c is my persisted counter used in the shared preferences.
Here's what I did at oncreate:
public String ID; //global
int checkCount = prefs.getInt("ID", c); //get the current ID value currently set or last set.
if( checkCount > 100)
{
c = checkCount; //whatever the value of c is from its latest increment the counter c set to this
}
else if (checkCount <= 100)
{
c = 100; //base value of clientIDs //assign base value for starting clientIDs
}
ID = "" + c + ""; //sets value of the counter to a string
//Parsing integer was not passing correctly.
clientID.setText(ID);
In the onclick:
//Once all the conditions are met pass the clientID for this instance.
SharedPreferences.Editor editor = prefs.edit(); //USING EDITOR TO ADD TO THE PREFERENCES
editor.putInt("ID", c);
....// then other stuff.
Any thoughts? My apologies if this is a noob question. I just want to be sure about this approach if this app goes all the way.
Thanks

Another Android Activity or an iterative JAVA method?

I am new to Android application development and am trying to find a way to proceed through a series of screens that take in user input. I'm making a small math game where the user would answer basic two integer addition problems. So far the main menu is created. It has a New Game button which launches my GameActivity and it runs just fine for one math problem. However, after the user inputs their answer to the simple math problem, I would like to be able to continue on to another math problem once the user had answered the current problem and the method would return a correct/incorrect value. Initially I thought of doing something like a basic FOR loop from within the GameActivity :
for(int i = 0; i < 10; i++){ gameMethod(); }
gameMethod() is a JAVA method that simply generates 2 random numbers, adds them to get the correct answer and then prompts the user using an EditText field to type in their guess. It displays the random numbers and answer using TextView boxes created in an XML layout file.
Each call to the gameMethod would, at least I think, just re-input the randomized numbers into the TextView fields displayed on the screen each iteration. I really don't care what the previous numbers were so I figured I would just overwrite them. I wan't able to get the code to do that though. I put in a Log.d() statement or two and found that the FOR loop was in fact running through correctly 10 times, but it was not waiting for user input before firing off its next gameMethod().
In doing some looking around, I found the startActivityForResult() and wondered if this was a more appropriate way of approaching this. So in this way, I foresee having three Activities, the Main menu which calls the GameActivity which would then iterate through, say 10 times, each iteration calling yet another activity GameScreenActivity which would actually put the numbers on the screen, read in user input and then return 1 for a correct answer and 0 for an incorrect answer. So far in reading up on StarActivityForResult() I'm getting somewhat confused by the process and wondered if this was even a plausible path to be exploring.
Again, I'm very new at this Android programming and appreciate any and all help that I can get.
Thank you.
Sorry for not including the gameMethod() initially, I've added it below.
// Create and initialize arrays of integers
int[] a = {0,1,2,3,4,5,6,7,8,9,10};
int[] b = {0,1,2,3,4,5,6,7,8,9,10};
// Creates random number generator
Random randy = new Random();
// Generates two random values to add
int r1 = randy.nextInt(10);
int r2 = randy.nextInt(10);
// Calculates correct answer
int an = a[r1] + a[r2];
// Displays 1st number
TextView number1 = (TextView) findViewById(R.id.firstNumber);
number1.setText(Integer.toString(a[r1]));
// Displays 2nd number
TextView number2 = (TextView) findViewById(R.id.secondNumber);
number2.setText(Integer.toString(b[r2]));
// Displays correct answer
TextView answer1 = (TextView) findViewById(R.id.answerNumber);
//hide answer until user puts in theirs
answer1.setVisibility(View.INVISIBLE);
answer1.setText(Integer.toString(an));
//hide the answer place holder value
TextView uAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber);
uAnswerDisplay.setVisibility(View.INVISIBLE);
//Get the EditText field that the user will input their answer to
EditText inputText = (EditText) findViewById(R.id.userInput);
//set up a listener to run once the ENTER key is hit after their answer has been entered
inputText.setOnKeyListener(new EditText.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
//only go on the ENTER key when pressed DOWN
if((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
EditText innerInputText = (EditText) findViewById(R.id.userInput); //get the EditText box reference
TextView innerUAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber); //get the TextView box that the answer will go in
String inputString = innerInputText.getText().toString(); //capture the user's input
int uAnswer = Integer.parseInt(inputString); //parse user answer to an integer
int cAnswer = Integer.parseInt((((TextView) findViewById(R.id.answerNumber)).getText()).toString());
innerUAnswerDisplay.setText(Integer.toString(uAnswer)); //display the string after converting from integer
//change colors of text based on correctness
if (uAnswer == cAnswer){ innerUAnswerDisplay.setTextColor(Color.GREEN); } //green for correct
else { innerUAnswerDisplay.setTextColor(Color.RED); } //red for incorrect
innerUAnswerDisplay.setVisibility(View.VISIBLE); //make the user input answer visible
TextView innerAnswer1 = (TextView) findViewById(R.id.answerNumber);
innerAnswer1.setVisibility(View.VISIBLE); //hide answer until user puts in theirs
} //end of if
return false; //return false
} //end of onKey
}); //end of setOnKeyListener
Sorry for all the edits, I couldn't get the edits to include the code and post correctly so I broke it up into chunks and added a little at a time.
From what you say, I'd consider two ways of letting the user answer questions:
have an onclick listener on the input EditText that triggers a new loop;
have a dialog activity that gets started in the beginning of the loop, which prompts the user for a new answer, your game activity would receive the answer via its onActivityResult.

Categories