save variables on screen rotation in android app - java

When I rotate screen in my android app, variables (fouls, goals and so on) get reset. I would like they don't reset on screen rotation. How can I do?
I know the problem is related to activity life-cycle, but I'm NOT able to solve it, since I develop from a very shot time (2 months).
This is the MainActivity.java
package com.marconota.serieasoccerscorekeeper;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.commons.lang3.StringUtils;
import java.lang.String;
public class MainActivity extends AppCompatActivity {
String scorerNames = "Marcatori: ";
String lastScorer = "";
int goalsForTeamA = 0;
int goalsForTeamB = 0;
int shotsForTeamA = 0;
int shotsForTeamB = 0;
int foulsForTeamA = 0;
int foulsForTeamB = 0;
int cornersForTeamA = 0;
int cornersForTeamB = 0;
int yellowCardsForTeamA = 0;
int yellowCardsForTeamB = 0;
int redCardsForTeamA = 0;
int redCardsForTeamB = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Displays scorers list
public void displayScorers(String score) {
TextView scoreView = (TextView) findViewById(R.id.listaMarcatori);
scoreView.setText(String.valueOf(score));
}
/**
* Displays score for Team A.
*/
public void displayGoalsForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.showGoalsForTeamA);
scoreView.setText(String.valueOf(score));
}
/**
* Displays score for Team B.
*/
public void displayGoalsForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.showGoalsForTeamB);
scoreView.setText(String.valueOf(score));
}
/**
* Displays shots for Team A.
*/
public void displayShotsForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.showShotsForTeamA);
scoreView.setText(String.valueOf(score));
}
/**
* Displays shots for Team B.
*/
public void displayShotsForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.showShotsForTeamB);
scoreView.setText(String.valueOf(score));
}
/**
* Displays corners for Team A.
*/
public void displayCornersForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.showCornersForTeamA);
scoreView.setText(String.valueOf(score));
}
/**
* Displays corners for Team B.
*/
public void displayCornersForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.showCornersForTeamB);
scoreView.setText(String.valueOf(score));
}
/**
* Displays fouls for Team A.
*/
public void displayFoulsForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.showFoulsForTeamA);
scoreView.setText(String.valueOf(score));
}
/**
* Displays fouls for Team B.
*/
public void displayFoulsForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.showFoulsForTeamB);
scoreView.setText(String.valueOf(score));
}
/**
* Displays yellow cards for Team A.
*/
public void displayYellowCardsForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.showYellowCardsForTeamA);
scoreView.setText(String.valueOf(score));
}
/**
* Displays yellow cards for Team B.
*/
public void displayYellowCardsForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.showYellowCardsForTeamB);
scoreView.setText(String.valueOf(score));
}
/**
* Displays red cards for Team A.
*/
public void displayRedCardsForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.showRedCardsForTeamA);
scoreView.setText(String.valueOf(score));
}
/**
* Displays red cards for Team B.
*/
public void displayRedCardsForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.showRedCardsForTeamB);
scoreView.setText(String.valueOf(score));
}
// Adds goal for team A
public void addOneGoalForTeamA(View view) {
goalsForTeamA = goalsForTeamA + 1;
displayGoalsForTeamA(goalsForTeamA);
}
// Adds goal for team B
public void addOneGoalForTeamB(View view) {
goalsForTeamB = goalsForTeamB + 1;
displayGoalsForTeamB(goalsForTeamB);
}
// Subtracts goal for team A and prevents stat provides negative number
public void subtractOneGoalForTeamA(View view) {
if (goalsForTeamA>0)
{goalsForTeamA = goalsForTeamA - 1;
displayGoalsForTeamA(goalsForTeamA);
}
else
{goalsForTeamA = 0;
displayGoalsForTeamA(goalsForTeamA);
}
}
// Subtracts goal for team B and prevents stat provides negative number
public void subtractOneGoalForTeamB(View view) {
if (goalsForTeamB>0)
{goalsForTeamB = goalsForTeamB - 1;
displayGoalsForTeamB(goalsForTeamB);
}
else
{goalsForTeamB = 0;
displayGoalsForTeamB(goalsForTeamB);
}
}
// Adds shot for team A
public void addOneShotForTeamA(View view) {
shotsForTeamA = shotsForTeamA + 1;
displayShotsForTeamA(shotsForTeamA);
}
// Adds shot for team B
public void addOneShotForTeamB(View view) {
shotsForTeamB = shotsForTeamB + 1;
displayShotsForTeamB(shotsForTeamB);
}
// Subtracts shot for team A and prevents stat provides negative number
public void subtractOneShotForTeamA(View view) {
if (shotsForTeamA>0)
{shotsForTeamA = shotsForTeamA - 1;
displayShotsForTeamA(shotsForTeamA);
}
else
{shotsForTeamA = 0;
displayShotsForTeamA(shotsForTeamA);
}
}
// Subtracts shot for team B and prevents stat provides negative number
public void subtractOneShotForTeamB(View view) {
if (shotsForTeamB>0)
{shotsForTeamB = shotsForTeamB - 1;
displayShotsForTeamB(shotsForTeamB);
}
else
{shotsForTeamB = 0;
displayShotsForTeamB(shotsForTeamB);
}
}
// Adds corner for team A
public void addOneCornerForTeamA(View view) {
cornersForTeamA = cornersForTeamA + 1;
displayCornersForTeamA(cornersForTeamA);
}
// Adds corner for team B
public void addOneCornerForTeamB(View view) {
cornersForTeamB = cornersForTeamB + 1;
displayCornersForTeamB(cornersForTeamB);
}
// Subtracts corner for team A and prevents stat provides negative number
public void subtractOneCornerForTeamA(View view) {
if (cornersForTeamA>0)
{cornersForTeamA = cornersForTeamA - 1;
displayCornersForTeamA(cornersForTeamA);
}
else
{cornersForTeamA = 0;
displayCornersForTeamA(cornersForTeamA);
}
}
// Subtracts corner for team B and prevents stat provides negative number
public void subtractOneCornerForTeamB(View view) {
if (cornersForTeamB>0)
{cornersForTeamB = cornersForTeamB - 1;
displayCornersForTeamB(cornersForTeamB);
}
else
{cornersForTeamB = 0;
displayCornersForTeamB(cornersForTeamB);
}
}
// Adds foul for team A
public void addOneFoulForTeamA(View view) {
foulsForTeamA = foulsForTeamA + 1;
displayFoulsForTeamA(foulsForTeamA);
}
// Adds foul for team B
public void addOneFoulForTeamB(View view) {
foulsForTeamB = foulsForTeamB + 1;
displayFoulsForTeamB(foulsForTeamB);
}
// Subtracts foul for team A and prevents stat provides negative number
public void subtractOneFoulForTeamA(View view) {
if (foulsForTeamA>0)
{foulsForTeamA = foulsForTeamA - 1;
displayFoulsForTeamA(foulsForTeamA);
}
else
{foulsForTeamA = 0;
displayFoulsForTeamA(foulsForTeamA);
}
}
// Subtracts foul for team B and prevents stat provides negative number
public void subtractOneFoulForTeamB(View view) {
if (foulsForTeamB>0)
{foulsForTeamB = foulsForTeamB - 1;
displayFoulsForTeamB(foulsForTeamB);
}
else
{foulsForTeamB = 0;
displayFoulsForTeamB(foulsForTeamB);
}
}
// Adds yellow card for team A
public void addOneYellowCardForTeamA(View view) {
yellowCardsForTeamA = yellowCardsForTeamA + 1;
displayYellowCardsForTeamA(yellowCardsForTeamA);
}
// Adds yellow card for team B
public void addOneYellowCardForTeamB(View view) {
yellowCardsForTeamB = yellowCardsForTeamB + 1;
displayYellowCardsForTeamB(yellowCardsForTeamB);
}
// Subtracts yellow card for team A and prevents stat provides negative number
public void subtractOneYellowCardForTeamA(View view) {
if (yellowCardsForTeamA>0)
{yellowCardsForTeamA = yellowCardsForTeamA - 1;
displayYellowCardsForTeamA(yellowCardsForTeamA);
}
else
{yellowCardsForTeamA = 0;
displayYellowCardsForTeamA(yellowCardsForTeamA);
}
}
// Subtracts yellow card for team B and prevents stat provides negative number
public void subtractOneYellowCardForTeamB(View view) {
if (yellowCardsForTeamB>0)
{yellowCardsForTeamB = yellowCardsForTeamB - 1;
displayYellowCardsForTeamB(yellowCardsForTeamB);
}
else
{yellowCardsForTeamB = 0;
displayYellowCardsForTeamB(yellowCardsForTeamB);
}
}
// Adds red card for team A
public void addOneRedCardForTeamA(View view) {
redCardsForTeamA = redCardsForTeamA + 1;
displayRedCardsForTeamA(redCardsForTeamA);
}
// Adds red card for team B
public void addOneRedCardForTeamB(View view) {
redCardsForTeamB = redCardsForTeamB + 1;
displayRedCardsForTeamB(redCardsForTeamB);
}
// Subtracts red card for team A and prevents stat provides negative number
public void subtractOneRedCardForTeamA(View view) {
if (redCardsForTeamA>0)
{redCardsForTeamA = redCardsForTeamA - 1;
displayRedCardsForTeamA(redCardsForTeamA);
}
else
{redCardsForTeamA = 0;
displayRedCardsForTeamA(redCardsForTeamA);
}
}
// Subtracts red card for team B and prevents stat provides negative number
public void subtractOneRedCardForTeamB(View view) {
if (redCardsForTeamB>0)
{redCardsForTeamB = redCardsForTeamB - 1;
displayRedCardsForTeamB(redCardsForTeamB);
}
else
{redCardsForTeamB = 0;
displayRedCardsForTeamB(redCardsForTeamB);
}
}
// Resets match stats
public void resetMatchStats(View view) {
scorerNames = "Marcatori: ";
displayScorers(scorerNames);
lastScorer = "";
goalsForTeamA = 0;
displayGoalsForTeamA(goalsForTeamA);
goalsForTeamB = 0;
displayGoalsForTeamB(goalsForTeamB);
shotsForTeamA = 0;
displayShotsForTeamA(shotsForTeamA);
shotsForTeamB = 0;
displayShotsForTeamB(shotsForTeamB);
foulsForTeamA = 0;
displayFoulsForTeamA(foulsForTeamA);
foulsForTeamB = 0;
displayFoulsForTeamB(foulsForTeamB);
cornersForTeamA = 0;
displayCornersForTeamA(cornersForTeamA);
cornersForTeamB = 0;
displayCornersForTeamB(cornersForTeamB);
yellowCardsForTeamA = 0;
displayYellowCardsForTeamA(yellowCardsForTeamA);
yellowCardsForTeamB = 0;
displayYellowCardsForTeamB(yellowCardsForTeamB);
redCardsForTeamA = 0;
displayRedCardsForTeamA(redCardsForTeamA);
redCardsForTeamB = 0;
displayRedCardsForTeamB(redCardsForTeamB);
}
//Adds last scorer in editText to scorers list and displays the updated scorers list
//If the add scorer field is empty, it doesn't update variable lastScorer.
//Else it takes the value from add scorer field, assign it to variable lastScorer, then it displays updated scorers
public void addScorer(View view) {
EditText addScorer = (EditText) findViewById(R.id.addScorerField);
String lastScorerPrep = addScorer.getText().toString();
if (StringUtils.isEmpty(lastScorerPrep))
{
}
else {
lastScorer = lastScorerPrep;
scorerNames = scorerNames + lastScorer + ", ";
displayScorers(scorerNames);
}
}
//Deletes last scorer from scorers list
public void deleteLastScorer(View view) {
scorerNames = scorerNames.replaceFirst((lastScorer + ", "), "");
displayScorers(scorerNames);
}
}
Thank you for helping me.

I solved, saving variables by putting them in the bundle savedInstanceState of method onSaveInstanceState and then getting them again from the bundle in the method onResumeInstanceState. This is java code:
// Saves variables in Bundle savedInstanceState
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("GoalsForTeamA", goalsForTeamA);
savedInstanceState.putInt("GoalsForTeamB", goalsForTeamB);
savedInstanceState.putInt("ShotsForTeamA", shotsForTeamA);
savedInstanceState.putInt("ShotsForTeamB", shotsForTeamB);
savedInstanceState.putInt("CornersForTeamA", cornersForTeamA);
savedInstanceState.putInt("CornersForTeamB", cornersForTeamB);
savedInstanceState.putInt("FoulsForTeamA", foulsForTeamA);
savedInstanceState.putInt("FoulsForTeamB", foulsForTeamB);
savedInstanceState.putInt("YellowCardsForTeamA", yellowCardsForTeamA);
savedInstanceState.putInt("YellowCardsForTeamB", yellowCardsForTeamB);
savedInstanceState.putInt("RedCardsForTeamA", redCardsForTeamA);
savedInstanceState.putInt("RedCardsForTeamB", redCardsForTeamB);
savedInstanceState.putString("ScorerNames",scorerNames );
savedInstanceState.putString("LastScorer", lastScorer );
}
// Gets variables from Bundle savedInstanceState and displays them again.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
goalsForTeamA = savedInstanceState.getInt("GoalsForTeamA");
goalsForTeamB = savedInstanceState.getInt("GoalsForTeamB");
shotsForTeamA = savedInstanceState.getInt("ShotsForTeamA");
shotsForTeamB = savedInstanceState.getInt("ShotsForTeamB");
foulsForTeamA = savedInstanceState.getInt("FoulsForTeamA");
foulsForTeamB = savedInstanceState.getInt("FoulsForTeamB");
cornersForTeamA = savedInstanceState.getInt("CornersForTeamA");
cornersForTeamB = savedInstanceState.getInt("CornersForTeamB");
yellowCardsForTeamA = savedInstanceState.getInt("YellowCardsForTeamA");
yellowCardsForTeamB = savedInstanceState.getInt("YellowCardsForTeamB");
redCardsForTeamA = savedInstanceState.getInt("RedCardsForTeamA");
redCardsForTeamB = savedInstanceState.getInt("RedCardsForTeamB");
scorerNames = savedInstanceState.getString("ScorerNames");
lastScorer = savedInstanceState.getString("LastScorer");
displayGoalsForTeamA(goalsForTeamA);
displayGoalsForTeamB(goalsForTeamB);
displayShotsForTeamA(shotsForTeamA);
displayShotsForTeamB(shotsForTeamB);
displayFoulsForTeamA(foulsForTeamA);
displayFoulsForTeamB(foulsForTeamB);
displayCornersForTeamA(cornersForTeamA);
displayCornersForTeamB(cornersForTeamB);
displayYellowCardsForTeamA(yellowCardsForTeamA);
displayYellowCardsForTeamB(yellowCardsForTeamB);
displayRedCardsForTeamA(redCardsForTeamA);
displayRedCardsForTeamB(redCardsForTeamB);
displayScorers(scorerNames);
}

Related

Disabling onClick until int = something

public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.

Android Quiz app crashing while updating score

The submit button id is ShowScore
correct answers are right1,right2...right53
when the button is clicked the app crashes...
android studios doest show any errors
right answer awards 1 point
wrong answer is -1
please help me out
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setScore() {
RadioButton check1 = (RadioButton) findViewById(R.id.right1);
boolean doit1 = check1.isChecked();
RadioButton check2 = (RadioButton) findViewById(R.id.right2);
boolean doit2 = check2.isChecked();
RadioButton check3 = (RadioButton) findViewById(R.id.right3);
boolean doit3 = check3.isChecked();
RadioButton check4 = (RadioButton) findViewById(R.id.right4);
boolean doit4 = check4.isChecked();
CheckBox check5 = (CheckBox) findViewById(R.id.right51);
boolean doit5 = check5.isChecked();
CheckBox check52 = (CheckBox) findViewById(R.id.right52);
boolean doit52 = check52.isChecked();
CheckBox check53 = (CheckBox) findViewById(R.id.right53);
boolean doit53 = check53.isChecked();
updateScore(doit1);
updateScore2(doit2);
updateScore3(doit3);
updateScore4(doit4);
updateScore5(doit5, doit52, doit53);
showScore();
}
private int updateScore(boolean doit1) {
if (doit1) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore2(boolean doit2) {
if (doit2) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore3(boolean doit3) {
if (doit3) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore4(boolean doit4) {
if (doit4) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
if (doit5 && doit52 && doit53) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private void showScore() {
TextView olds = (TextView) findViewById(R.id.ShowScore);
olds.setText(score);
}
}
#. I guess you have defined setScore() method to SUBMIT Button in your XML using attribute android:onClick="setScore". But your method doesn't have any View parameter. Update your method as below:
public void setScore(View v) {
..........
.............
}
#. As score is an int value, use olds.setText(String.valueOf(score)) to set score on TextView.
Here is the full code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView olds;
RadioButton check1, check2, check3, check4;
CheckBox check5, check52, check53;
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
olds = (TextView) findViewById(R.id.ShowScore);
check1 = (RadioButton) findViewById(R.id.right1);
check2 = (RadioButton) findViewById(R.id.right2);
check3 = (RadioButton) findViewById(R.id.right3);
check4 = (RadioButton) findViewById(R.id.right4);
check5 = (CheckBox) findViewById(R.id.right51);
check52 = (CheckBox) findViewById(R.id.right52);
check53 = (CheckBox) findViewById(R.id.right53);
}
public void setScore(View v) {
boolean doit1 = check1.isChecked();
boolean doit2 = check2.isChecked();
boolean doit3 = check3.isChecked();
boolean doit4 = check4.isChecked();
boolean doit5 = check5.isChecked();
boolean doit52 = check52.isChecked();
boolean doit53 = check53.isChecked();
updateScore(doit1);
updateScore2(doit2);
updateScore3(doit3);
updateScore4(doit4);
updateScore5(doit5, doit52, doit53);
showScore();
}
private int updateScore(boolean doit1) {
if (doit1) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore2(boolean doit2) {
if (doit2) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore3(boolean doit3) {
if (doit3) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore4(boolean doit4) {
if (doit4) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
if (doit5 && doit52 && doit53) {
score = score + 1;
} else {
score = score - 1;
}
return score;
}
private void showScore() {
olds.setText(String.valueOf(score));
}
}
Change setText.(score) to (score+"");
Explanation: setText method accepts only String as an argument but yes you can pass in an int but it will give an error and I suppose that output stream in android platform must always be String type.
You can even use String.valueOf(score); since this is the right way and adding quotation marks set in the first paramater is like a geek cheat. If you have set onClick method in xml, then setScore() must take the parameter setScore (View view) { //text view goes here..}
Hope it works. Cheers!

Why doesn't the following piece of code input data properly?

package com.example.my.galgu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
long first=1, second=1, answer;
boolean a=false ,s=false ,m=false ,d=false;
int i=0;
String wholesome, goti;
Button ba, bs, bm, bd, be;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
ba = (Button) findViewById(R.id.ba);
bs = (Button) findViewById(R.id.bs);
bm = (Button) findViewById(R.id.bm);
bd = (Button) findViewById(R.id.bd);
be = (Button) findViewById(R.id.be);
be.setEnabled(false);
}
public void disable(){
ba.setEnabled(false);
bs.setEnabled(false);
bm.setEnabled(false);
bd.setEnabled(false);
}
A method for each of the buttons from one to zero.
The problem lies somewhere in the below method where the first and second
are stored. The method first checks if any of the +,-,*,/ buttons are
pressed and then stores the value in either the first or second variable.
The last digit for the first variable is omitted. And I can't say why.
public void onone(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 1;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("1");
else{
textView.setText(wholesome + "1");
}
}
public void ontwo(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 2;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("2");
else{
textView.setText(wholesome + "2");
}
}
public void onthree(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 3;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("3");
else{
textView.setText(wholesome + "3");
}
}
public void onfour(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 4;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("4");
else{
textView.setText(wholesome + "4");
}
}
public void onfive(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 5;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("5");
else{
textView.setText(wholesome + "5");
}
}
public void onsix(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 6;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("6");
else{
textView.setText(wholesome + "6");
}
}
public void onseven(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 7;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("7");
else{
textView.setText(wholesome + "7");
}
}
public void oneight(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 8;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("8");
else{
textView.setText(wholesome + "8");
}
}
public void onnine(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 9;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("9");
else{
textView.setText(wholesome + "9");
}
}
public void onzero(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 1;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("0");
else{
textView.setText(wholesome + "0");
}
}
public void ona(View view){
a = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "+");
disable();
be.setEnabled(true);
}
public void ons(View view){
s = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "-");
disable();
be.setEnabled(true);
}
public void onm(View view){
m = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "*");
disable();
be.setEnabled(true);
}
public void ond(View view){
d = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "/");
disable();
be.setEnabled(true);
}
public void one(View view){
if(a){
answer = first + second;
}
else if (s){
answer = first - second;
}
else if (m){
answer = first * second;
}
else if (d){
answer = first / second;
}
goti = String.valueOf(answer);
textView.setText(goti);
second = 1;
i = 0;
a = false;
s = false;
m = false;
d = false;
ba.setEnabled(true);
bs.setEnabled(true);
bm.setEnabled(true);
bd.setEnabled(true);
}
public void once(View view){
textView.setText("0");
second = 1;
i = 0;
ba.setEnabled(true);
bs.setEnabled(true);
bm.setEnabled(true);
bd.setEnabled(true);
be.setEnabled(false);
a = false;
s = false;
m = false;
d = false;
}
}

Android Application Button onclicklistener

Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class

Achartengine's piechart does not refresh from repaint function

I'm building an application that makes piechart from database according to precise date interval. Unfortunately the achartengine's repaint function is not working when I'm stepping with the buttons.
When the Activity starts everything is fine the chart is okay but when i'm using the buttons then nothing happens.
I hope somebody can help me.
here is the code:
private GraphicalView chartView;
...
tabHost.addTab(tabHost.newTabSpec("").setIndicator("Grafikon")
.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String arg0) {
final View view = LayoutInflater.from(SumMenuActivity.this).inflate(
R.layout.summenu_tab3, null);
periodSeekBar = (SeekBar) view.findViewById(R.id.summenutab3_periodslide);
final TextView periodName = (TextView) view
.findViewById(R.id.summenutab3_periodtw);
if (chartView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.chart);
intValChanger(intVal, 0);
layout.addView(chartView);
} else {
chartView.repaint();
}
periodSeekBar
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (progress == 0) {
periodName.setText("Heti");
} else if (progress == 1) {
periodName.setText("Havi");
} else if (progress == 2) {
periodName.setText("Eves");
}
intVal = 0;
intValChanger(intVal, progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final View minusButton = view.findViewById(R.id.summenutab3_frombutton);
final View plusButton = view.findViewById(R.id.summenutab3_tobutton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intVal--;
intValChanger(intVal, periodSeekBar.getProgress());
if (chartView != null) {
chartView.refreshDrawableState();
chartView.repaint();
}
}
});
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intVal++;
intValChanger(intVal, periodSeekBar.getProgress());
if (chartView != null) {
chartView.refreshDrawableState();
chartView.repaint();
}
}
});
return view;
}
...
public void intValChanger(int intVal, int type) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
if (type == 0) {
start.setFirstDayOfWeek(Calendar.MONDAY);
end.setFirstDayOfWeek(Calendar.MONDAY);
int currentStartOfWeek = (start.get(Calendar.DAY_OF_WEEK) + 7 - start
.getFirstDayOfWeek()) % 7;
int currentEndOfWeek = (end.get(Calendar.DAY_OF_WEEK) + 7 - end.getFirstDayOfWeek()) % 7;
start.add(Calendar.DAY_OF_YEAR, -currentStartOfWeek + intVal * 7);
end.add(Calendar.DAY_OF_YEAR, (-currentEndOfWeek + intVal * 7) + 6);
} else if (type == 1) {
start.set(Calendar.DATE, 1);
start.set(Calendar.MONTH, start.get(Calendar.MONTH) + 1 * intVal);
end.set(Calendar.DATE, start.getActualMaximum(Calendar.DATE));
end.set(Calendar.MONTH, end.get(Calendar.MONTH) + 1 * intVal);
} else if (type == 2) {
start.set(Calendar.YEAR, start.get(Calendar.YEAR) + 1 * intVal);
start.set(Calendar.MONTH, 0);
start.set(Calendar.DATE, 1);
end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1 * intVal);
end.set(Calendar.MONTH, 11);
end.set(Calendar.DATE, 31);
}
if (tabHost.getCurrentTab() == 0) {
populateTimeList(start.getTime(), end.getTime());
} else if (tabHost.getCurrentTab() == 1) {
populateSumArrayList(start.getTime(), end.getTime());
} else if (tabHost.getCurrentTab() == 2) {
populateChart(start.getTime(), end.getTime());
}
Toast.makeText(getApplicationContext(),
android.text.format.DateFormat.format("yyyy-MM-dd", start) +
"-tól " + android.text.format.DateFormat.format("yyyy-MM-dd", end)
+ "-ig", 3).show();
}
public GraphicalView executeChart(Context context, ArrayList<String> name,
ArrayList<Integer> value) {
ArrayList<Integer> colors = new ArrayList<Integer>();
CategorySeries categorySeries = new CategorySeries("Torta diagram");
for (int i = 0; i < name.size(); i++) {
Random r = new Random();
categorySeries.add(name.get(i), value.get(i));
colors.add(Color.rgb(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
}
DefaultRenderer renderer = buildCategoryRenderer(colors);
renderer.setLabelsTextSize(14);
GraphicalView gview = ChartFactory.getPieChartView(context,
categorySeries, renderer);
return gview;
}
protected DefaultRenderer buildCategoryRenderer(ArrayList<Integer> colors) {
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
public void populateChart(Date from, Date to) {
ArrayList<String> tmpName = new ArrayList<String>();
ArrayList<Integer> tmpValue = new ArrayList<Integer>();
ArrayList<Category> tmpCategory = getCategories();
ArrayList<Transaction> tmpTransaction = new ArrayList<Transaction>();
for (int i = 0; i < tmpCategory.size(); i++) {
tmpName.add(tmpCategory.get(i).getName());
tmpTransaction = (ArrayList<Transaction>) getTransactionsByTimeIntvalAndId(from, to,
tmpCategory.get(i).getId());
int ammount = 0;
for (int j = 0; j < tmpTransaction.size(); j++) {
ammount += tmpTransaction.get(j).getAmmount();
}
tmpValue.add(ammount);
}
for (int i = 0; i < tmpName.size(); i++) {
Log.d("DEBUG MESSAGE", tmpName.get(i) + ": " + tmpValue.get(i));
}
chartView = null;
chartView = executeChart(SumMenuActivity.this, tmpName, tmpValue);
Log.d("DEBUG MESSAGE", "megtörtént a repaint!" + chartView);
}
I have not used Achart but this is a simple pie chart implementation. You can refer the demo and it might help.
In this demo after you update the values, you need to call invalidate() to redraw the pie chart.
https://github.com/blessenm/PieChartDemo

Categories