I'm trying to make a game and can't seem to get the score counter to work. The problem is that every time the button is clicked the value of the integer goes back to 0.
public void button(View view){
Integer counter = Integer.valueOf(0);
counter = counter++;
final TextView score = (TextView) findViewById(R.id.score);
score.setText("Score: " + counter);
}
I obviously see why the score goes back to 0 every time but I don't know how to fix it. I'm new with development so some sample code would be appreciated. Thanks.
Here's some modified code from http://developer.android.com/reference/android/widget/Button.html
public class MyActivity extends Activity {
int counter = 0; // Counter variable.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter = counter++;
final TextView score = (TextView) findViewById(R.id.score);
score.setText("Score: " + counter);
}
});
}
}
This should do what you want. Hope it helps!
Because you are resetting it.
Integer counter = Integer.valueOf(0); // here
counter = counter++;
Use it a global variable instead.
public class MyActivity extends Activity{
int counter;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(...);
counter = 0;
}
public void button(View view){
counter = counter++;
final TextView score = (TextView) findViewById(R.id.score);
score.setText("Score: " + counter);
}
}
What you need to do is to initialize your counter in a more persistent part of your program or even as a global variable. Each time you call your function, you are initializing a new counter.
In order to tackle this problem, you should research variable scope.
(Sample link from a Google Search for "Java variable scope".(1) )
Related
Learning how to produce random numbers from arrays. The code will pick a random string during the onCreate method, but when the button is clicked there is no change to the string. Am I messing up the scope of my variables somehow? I really do not know what it wrong.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
}
public void onClick(View view){
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
TextView question = (TextView) findViewById(R.id.question);
question.setText(q);
}
});
}
}
First of all you haven't set click listener on button properly you made onClick method which is never called . Also you are getting the references of view multiple times you should do it like this.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
question.setText(q);
}
});
}
}
You either need to set the onClickListener in xml (in which case you don't need to set the listener in code), or you need to set the listener in onCreate. Right now its being set in a function named onClick, which is never called.
First, you never set the onClickListeren. You have a method which adds one, but you never call it. Move the code in the onClick method to your onCreate method. This will probably fix your problem.
If not, don't make your Random final and add this to your #Override onClick():
rgen = new Random(System.currentTimeMillis());
This will use a different seed every time
Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}
I have a problem when it comes to create a high score view. The point of the game is to click as many times as you can on a button in 15 seconds and I would like to make appear a high score in the right corner for instance. Here is my code:
public class newgame extends Activity {
int clicks = 0;
TextView textCount;
Button buttonCount;
int guessCount =0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (Button) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView)findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
CountDownTimer Count = new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
Count.start();
}
How would I go proceed to achieve this?
Add a value to sharedPreferences
getSharedPreferences("myPrefs", MODE_PRIVATE).putInt("highscore", clicks).commit();
Retrieve a value frome sharedPreferences
getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
implemented:
public class newgame extends Activity {
int clicks = 0;
TextView textCount;
Button buttonCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.textView);
buttonCount = (Button) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks + "(old highscore = " + oldscore + ")");
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
CountDownTimer Count = new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
Count.start();
}
}
Your code can do with some tweaking though
Zhuinden's comment is pretty much what you want. But I'll try to suggest something that might be just fit straight in - although I would suggest you experiment with these things yourself a bit
Add the following variables:
int topScore = 0;
SharedPreferences prefs;
Add this to your onCreate method
prefs = _context.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
TextView topScore = (TextView) findViewById(R.id.topScoreView);
topScore.setText(prefs.getInt("topScore", 0);
Change your onFinish to the following:
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (guessCount > topScore) {
prefs.edit().putInt("topScore", guessCount).apply();
}
}
This should work I think but haven't actually tested it
Okay, in order to use shared preferences to store the score value you have stored in the guessCount variable, you'll first need to get the shared preferences for your application. To do this, you can use:
SharedPreferences sharedPrefs = this.getSharedPreferences(
"com.example.yourAppName", Context.MODE_PRIVATE);
Once this is done, you can add the score value into the preferences by using:
sharedPrefs.putInt("High Score", guessCount).apply();
Then later when you want to retrieve the high score for use, you'll need to make sure you still have a SharedPreferences object in the manner I described above, but to read data from it you just use:
int retrieveCount = sharedPrefs.getInt("High Score", 0)
The value in retrieveCount will be whatever you stored earlier. Be careful to make sure that there is a value stored in SharedPreferences or you will get back 0.
Additionally:
Android Documentation for SharedPreference
In an android app I intend to allow users to answer a random sum then a new one appears on screen. This is repeated 10 times and then a final score will then be given. However I am unsure how to update the sum so that after each each a new random is shown on screen.
Below is my current code:
public class Test extends Activity {
//declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String question;
int correctAnswer;#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
//set up random
setUpRandom();
//Set text view equal to question
text.setText(question);
//updateQuestion?
}
public void initialiseVars() {
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
}
public void setUpRandom() {
//setting up randoms
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
question = random1 + " x " + random2 + " = ";
correctAnswer = random1 * random2;
}
public void updateQuestion() {
//CODE TO UPDATE QUESTION
}
}
Add Button ClickListener so that when user press submit button it will update question and clean all previous values
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateQuestion();
}
}
Maintain a count in your activity and increase it in updateQuestion
public void updateQuestion() {
if (Int.parseString(answer.getText().toString()) != correctAnswer) {
// Show toast or something
return;
}
tries++;
if (tries == 10) return; // or do something else;
answer.setText("");
setUpRandom();
text.setText(question); // add this line in your setUpRandom();
}
To generate random integers look at this. Hopefully this will help you out.
It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.