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!
Related
I'm making a simple tic tac toe game but there's a pretty big issue. Basically, whenever there are any 3 symbols in a row (not necessarily 3 O's or 3 X's, just any three, the game thinks someone has won). I know that this is an issue with my checkWin method, but I'm not exactly sure what.
Something to note is that I named my buttons 1-10 instead of 0-9 which was a bad idea in hindsight as arrays start from 0. I think this might be causing my issue.
Here's what I've got so far with a screenshot of the app.
Many thanks,
Luke
package com.example.tictactoe;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView PlayerOneScore, PlayerTwoScore, winStatus;
private Button [] mButtons = new Button[10];
private Button reset;
private int PlayerOneScoreCount, PlayerTwoScoreCount, roundCount;
boolean PlayerTurn;
int [] gameState = {2,2,2,2,2,2,2,2,2,2};
int [][] winStates = {
{1,2,3},{4,5,6},{7,8,9},
{1,4,7},{2,5,8},{3,6,9},
{1,5,9},{3,5,7}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PlayerOneScore = (TextView)findViewById(R.id.P1Score);
PlayerTwoScore = (TextView)findViewById(R.id.P2Score);
winStatus = (TextView)findViewById(R.id.winStatus);
reset = (Button) findViewById(R.id.reset);
for (int i=1; i < mButtons.length; i++){
String buttonID = "btn" + i;
int resourceID = getResources().getIdentifier(buttonID, "id", getPackageName());
mButtons[i] = (Button) findViewById(resourceID);
mButtons[i].setOnClickListener(this);
}
roundCount = 0;
PlayerOneScoreCount = 0;
PlayerTwoScoreCount = 0;
PlayerTurn = true;
}
#Override
public void onClick(View v) {
if (!((Button)v).getText().toString().equals("")){
return;
}
String buttonID = v.getResources().getResourceEntryName(v.getId());
int gameStatePointer = Integer.parseInt(buttonID.substring
(buttonID.length()-1, buttonID.length()));
if (PlayerTurn){
((Button)v).setText("X");
((Button)v).setTextColor(Color.parseColor("#545454"));
gameState[gameStatePointer] = 0;
}else {
((Button)v).setText("O");
((Button)v).setTextColor(Color.parseColor("#F2EBD3"));
gameState[gameStatePointer] = 0;
}
roundCount++;
if(checkWin()){
if(PlayerTurn){
PlayerOneScoreCount++;
updatePlayerScore();
Toast.makeText(this, "Player One Won!", Toast.LENGTH_SHORT).show();
playAgain();
}else {
PlayerTwoScoreCount++;
updatePlayerScore();
Toast.makeText(this, "Player Two Won!", Toast.LENGTH_SHORT).show();
playAgain();
}
}else if(roundCount == 9){
playAgain();
Toast.makeText(this, "It's a Draw!", Toast.LENGTH_SHORT).show();
}else {
PlayerTurn = !PlayerTurn;
}
if (PlayerOneScoreCount > PlayerTwoScoreCount){
winStatus.setText("Player One is Winning!");
}else if (PlayerTwoScoreCount > PlayerOneScoreCount){
winStatus.setText("Player Two is Winning!");
}else {
winStatus.setText("");
}
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playAgain();
PlayerOneScoreCount = 0;
PlayerTwoScoreCount = 0;
winStatus.setText("");
updatePlayerScore();
}
});
}
public boolean checkWin(){
boolean Winner = false;
for (int [] winningState : winStates){
if (gameState[winningState[0]] == gameState[winningState[1]] &&
gameState[winningState[1]] == gameState[winningState[2]] &&
gameState[winningState[0]]!=2){
Winner = true;
}
}
return Winner;
}
public void updatePlayerScore(){
PlayerOneScore.setText(Integer.toString(PlayerOneScoreCount));
PlayerTwoScore.setText(Integer.toString(PlayerTwoScoreCount));
}
public void playAgain(){
roundCount = 0;
PlayerTurn = true;
for (int i = 1; i < mButtons.length; i++){
gameState[i] = 2;
mButtons[i].setText("");
}
}
}
In checkWin() you iterate through the various winning states to see if any of the players has won by comparing all Buttons which "belong" to a given winning state.
Since you always set the game state value to zero if a Button has been clicked, no matter whose turn it is, you will have a "winner" as soon as all Buttons belonging to one winning state have been clicked.
TL;DR You can fix the issue by setting different values in onClick() depending on whose turn it is:
if (PlayerTurn){
((Button)v).setText("X");
((Button)v).setTextColor(Color.parseColor("#545454"));
gameState[gameStatePointer] = 1;
}else {
((Button)v).setText("O");
((Button)v).setTextColor(Color.parseColor("#F2EBD3"));
gameState[gameStatePointer] = 0;
}
I'm not quite sure, but I think it might be the values you set in your gamestate. As far as I can see, you are always setting it to 0 in your onClick method
if (PlayerTurn){
((Button)v).setText("X");
((Button)v).setTextColor(Color.parseColor("#545454"));
gameState[gameStatePointer] = 0;
}else {
((Button)v).setText("O");
((Button)v).setTextColor(Color.parseColor("#F2EBD3"));
gameState[gameStatePointer] = 0;
}
Then when you are checking, whether the values in the gamestate are equal every field, which was clicked has a 0 in it, so the they are equal. You probably wanted to set on of them to another integer
Iam getting runtime error at Dialog fragment. At the Runtime of program works smoothly but when it comes to dialog appearence imes the program crashes........... Somebody show me where did the mistake I can't resolve my problem.
I am posting a LogCat Image because of body limit is crossed
MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
public static final String GUESSES = "settings_numberOfGuesses";
public static final String ANIMALS_TYPE = "settings_animalType";
public static final String QUIZ_BACKGROUND_COLOR = "settings_quiz_background_color";
public static final String QUIZ_FONT = "settings_quiz_font";
private boolean isSettingsChanged = false;
static Typeface azkiaDemo;
static Typeface chunkFive;
static Typeface fontleroyBrown;
static Typeface hauntedEyes;
static Typeface knightBrushDemo;
static Typeface wonderbarDemo;
MainActivityFragment myAnimalQuizFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
azkiaDemo = Typeface.createFromAsset(getAssets(),"fonts/Azkia demo.otf");
chunkFive = Typeface.createFromAsset(getAssets(),"fonts/Chunkfive.otf");
fontleroyBrown = Typeface.createFromAsset(getAssets(),"fonts/FontleroyBrown.ttf");
hauntedEyes = Typeface.createFromAsset(getAssets(),"fonts/Haunted Eyes.otf");
knightBrushDemo = Typeface.createFromAsset(getAssets(),"fonts/Knight Brush Demo.otf");
wonderbarDemo = Typeface.createFromAsset(getAssets(),"fonts/Wonderbar Demo.otf");
PreferenceManager.setDefaultValues(this, R.xml.quiz_preferences, false);
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(settingsChangedListener);
myAnimalQuizFragment = (MainActivityFragment) getSupportFragmentManager().findFragmentById(R.id.animalQuizFragment);
myAnimalQuizFragment.modifyAnimalGuessRows(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyTypeofAnimals(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyQuizFont(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyBackgroundColor(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.resetAnimalQuiz();
isSettingsChanged = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent preferencesIntent = new Intent(this,SettingsActivity.class);
startActivity(preferencesIntent);
return super.onOptionsItemSelected(item);
}
private SharedPreferences.OnSharedPreferenceChangeListener settingsChangedListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
isSettingsChanged = true;
if (key.equals(GUESSES)){
myAnimalQuizFragment.modifyAnimalGuessRows(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(ANIMALS_TYPE)){
Set<String> animalTypes = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
if (animalTypes != null && animalTypes.size() > 0){
myAnimalQuizFragment.modifyTypeofAnimals(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else {
SharedPreferences.Editor editor = sharedPreferences.edit();
animalTypes.add(getString(R.string.default_animal_type));
editor.putStringSet(ANIMALS_TYPE, animalTypes); // here we provided default value also.......
editor.apply();
Toast.makeText(MainActivity.this, R.string.default_animalType_message, Toast.LENGTH_SHORT).show();
}
}else if (key.equals(QUIZ_FONT)){
myAnimalQuizFragment.modifyQuizFont(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(QUIZ_BACKGROUND_COLOR)){
myAnimalQuizFragment.modifyBackgroundColor(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}
Toast.makeText(MainActivity.this, R.string.toast_message , Toast.LENGTH_SHORT).show();
}
};
public void showDialog(){
ExampleDialog exampleDialog = new ExampleDialog();
exampleDialog.setCancelable(false);
exampleDialog.show(getFragmentManager(),"Animal_Quiz_Result");
}
}
Here is the MainActivityFragment.java class
import android.animation.Animator;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MainActivityFragment extends Fragment {
public static final int NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ = 10;
private List<String> allAnimalsNameList;
private List<String> animalNamesQuizList;
private Set<String> animalTypesInQuiz;
private String correctAnimalsAnswer;
public static int numberOfAllGuesses;
private int numberOfAnimalGuessRows;
private int numberOfRightAnswers;
private SecureRandom secureRandomNumber;
private Handler handler;
private Animation wrongAnswerAnimation;
private LinearLayout animalQuizLinearLayout;
private TextView txtQuestionNumber;
private ImageView imgAnimal;
private LinearLayout[] rowsOfGuessButtonsInAnimalQuiz;
private TextView txtAnswer;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
allAnimalsNameList = new ArrayList<>();
animalNamesQuizList = new ArrayList<>();
secureRandomNumber = new SecureRandom();
handler = new Handler();
wrongAnswerAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.wrong_animation);
wrongAnswerAnimation.setRepeatCount(1);
animalQuizLinearLayout = view.findViewById(R.id.animalQuizLinearLayout);
txtQuestionNumber = view.findViewById(R.id.txtQuestionNumber);
imgAnimal = view.findViewById(R.id.imgAnimal);
rowsOfGuessButtonsInAnimalQuiz = new LinearLayout[3];
rowsOfGuessButtonsInAnimalQuiz[0] = view.findViewById(R.id.firstRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[1] = view.findViewById(R.id.secondRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[2] = view.findViewById(R.id.thirdRowLinearLayout);
txtAnswer = view.findViewById(R.id.txtAnswer);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz) {
for (int column = 0; column < row.getChildCount(); column++) {
Button btnGuess = (Button) row.getChildAt(column);
btnGuess.setOnClickListener(btnGuessListener);
btnGuess.setTextSize(24);
}
}
txtQuestionNumber.setText(getString(R.string.question_text, 1, NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
// getString is extends fragment...........
return view;
}
private View.OnClickListener btnGuessListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button btnGuess = ((Button) view);
String guessValue = btnGuess.getText().toString();
String answerValue = getTheExactAnimalName(correctAnimalsAnswer);
++numberOfAllGuesses;
if (guessValue.equals(answerValue)) {
++numberOfRightAnswers;
txtAnswer.setText(answerValue + " ! " + " RIGHT");
disableQuizGuessButton();
if (numberOfRightAnswers == NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
} else {
handler.postDelayed(new Runnable() {
#Override
public void run() {
animateAnimalQuiz(true);
}
}, 1000); //1000 milliseconds for 1 second delay.......
}
} else {
imgAnimal.startAnimation(wrongAnswerAnimation);
txtAnswer.setText(R.string.wrong_answer_message);
btnGuess.setEnabled(false);
}
}
};
public static String getTheExactAnimalName(String animalName) {
return animalName.substring(animalName.indexOf('-') + 1).replace('_', ' ');
}// this method changes the actual name of image for example removes or starts after tame_animal- through index of method
// and after that removes _ between the names of animals...........
private void disableQuizGuessButton() {
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
LinearLayout guessRowLinearLayout = rowsOfGuessButtonsInAnimalQuiz[row];
for (int buttonIndex = 0; buttonIndex < guessRowLinearLayout.getChildCount(); buttonIndex++) {
guessRowLinearLayout.getChildAt(buttonIndex).setEnabled(false);
}
}
}
public void resetAnimalQuiz() {
AssetManager assets = getActivity().getAssets();
allAnimalsNameList.clear();
try {
for (String animalType : animalTypesInQuiz) {
String[] animalImagePathsInQuiz = assets.list(animalType);
for (String animalImagePathInQuiz : animalImagePathsInQuiz) {
allAnimalsNameList.add(animalImagePathInQuiz.replace(".png", ""));
}
}
} catch (IOException e) {
Log.e("AnimalQuiz", "Error", e);
}
numberOfRightAnswers = 0; // this variable holds the right guesses must be 0 because we reset the game.
numberOfAllGuesses = 0; // this variable holds no. of all guesses whether it is right or wrong have to be 0.
animalNamesQuizList.clear(); // this variable holds randomly generated quiz paths must be 0 to generate new paths......
int counter = 1;
int numberOfAvailableAnimal = allAnimalsNameList.size();// this variable holds number of available animals or the size or length of paths
while (counter <= NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
int randomIndex = secureRandomNumber.nextInt(numberOfAvailableAnimal);
String animalImageName = allAnimalsNameList.get(randomIndex);
if (!animalNamesQuizList.contains(animalImageName)) {
animalNamesQuizList.add(animalImageName);
++counter;
}
}
showNextAnimal();
}
private void animateAnimalQuiz(boolean animateOutAnimalImage) {
if (numberOfRightAnswers == 0) {
return;
}
int xTopLeft = 0;
int yTopLeft = 0;
int xBottomRight = animalQuizLinearLayout.getLeft() + animalQuizLinearLayout.getRight();
int yBottomRight = animalQuizLinearLayout.getTop() + animalQuizLinearLayout.getBottom();
//Here is max value for radius
int radius = Math.max(animalQuizLinearLayout.getWidth(), animalQuizLinearLayout.getHeight());
Animator animator;
if (animateOutAnimalImage) {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xBottomRight, yBottomRight, radius, 0);
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
showNextAnimal();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
} else {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xTopLeft, yTopLeft, 0, radius);
}
animator.setDuration(700);
animator.start();
}
private void showNextAnimal() {
String nextAnimalImageName = animalNamesQuizList.remove(0);
correctAnimalsAnswer = nextAnimalImageName;
txtAnswer.setText("");
txtQuestionNumber.setText(getString(R.string.question_text, (numberOfRightAnswers + 1), NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
String animalType = nextAnimalImageName.substring(0, nextAnimalImageName.indexOf("-")); // it holds the animal type whether it is
// Tame animal or Wild Animal
AssetManager assets = getActivity().getAssets();
try (InputStream stream = assets.open(animalType + "/" + nextAnimalImageName + ".png")) {
Drawable animalImage = Drawable.createFromStream(stream, nextAnimalImageName);
imgAnimal.setImageDrawable(animalImage);
animateAnimalQuiz(false);
} catch (IOException e) {
Log.e("AnimalQuiz", "There is an Error Getting" + nextAnimalImageName, e);
}
Collections.shuffle(allAnimalsNameList); // this method is a predefined method in java which helps to shuffle the list of data
int correctAnimalNameIndex = allAnimalsNameList.indexOf(correctAnimalsAnswer);
String correctAnimalName = allAnimalsNameList.remove(correctAnimalNameIndex);
allAnimalsNameList.add(correctAnimalName);
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
for (int column = 0; column < rowsOfGuessButtonsInAnimalQuiz[row].getChildCount(); column++) {
Button btnGuess = (Button) rowsOfGuessButtonsInAnimalQuiz[row].getChildAt(column);
btnGuess.setEnabled(true);
String animalImageName = allAnimalsNameList.get((row * 2) + column);
btnGuess.setText(getTheExactAnimalName(animalImageName));
}
}
int row = secureRandomNumber.nextInt(numberOfAnimalGuessRows);
int column = secureRandomNumber.nextInt(2);
LinearLayout randomRow = rowsOfGuessButtonsInAnimalQuiz[row];
String correctAnimalImageName = getTheExactAnimalName(correctAnimalsAnswer);
((Button) randomRow.getChildAt(column)).setText(correctAnimalImageName);
}
public void modifyAnimalGuessRows(SharedPreferences sharedPreferences){
final String NUMBER_OF_GUESS_OPTION = sharedPreferences.getString(GUESSES,null);
numberOfAnimalGuessRows = Integer.parseInt(NUMBER_OF_GUESS_OPTION)/2;
for (LinearLayout horizontalLinearLayout : rowsOfGuessButtonsInAnimalQuiz){
horizontalLinearLayout.setVisibility(View.GONE);
}
for (int row = 0; row < numberOfAnimalGuessRows; row++){
rowsOfGuessButtonsInAnimalQuiz[row].setVisibility(View.VISIBLE);
}
}
public void modifyTypeofAnimals(SharedPreferences sharedPreferences){
animalTypesInQuiz = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
}
public void modifyQuizFont(SharedPreferences sharedPreferences){
String fontStringValue = sharedPreferences.getString(QUIZ_FONT,null);
switch (fontStringValue){
case "Chunkfive.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(chunkFive);
}
}
break;
case "Azkia demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(azkiaDemo);
}
}
break;
case "FontleroyBrown.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(fontleroyBrown);
}
}
break;
case "Haunted Eyes.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(hauntedEyes);
}
}
break;
case "Knight Brush Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(knightBrushDemo);
}
}
break;
case "Wonderbar Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(wonderbarDemo);
}
}
break;
}
}
public void modifyBackgroundColor(SharedPreferences sharedPreferences){
String backgroundColor = sharedPreferences.getString(QUIZ_BACKGROUND_COLOR,null);
switch (backgroundColor){
case "White":
animalQuizLinearLayout.setBackgroundColor(Color.WHITE);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.rgb(34,167,240));
break;
case "Black":
animalQuizLinearLayout.setBackgroundColor(Color.BLACK);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(247,202,24));
button.setTextColor(Color.BLACK);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Green":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(38,166,91));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.rgb(247,202,24));
txtAnswer.setTextColor(Color.WHITE);
break;
case "Yellow":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(247,202,24));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.BLACK);
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.BLACK);
break;
case "Red":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(240,52,52));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Blue":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(34,167,240));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(240,52,52));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
}
}
}
Here is the ExampleDialog.java class
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import static com.example.narayanmaity.app61animal_quiz.MainActivityFragment.numberOfAllGuesses;
/**
* Created by Narayan Maity on 12/14/2017.
*/
public class ExampleDialog extends DialogFragment {
MainActivityFragment myAnimalQuizFragment;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.results_string_value, numberOfAllGuesses,
(1000 / (double) numberOfAllGuesses)));
builder.setPositiveButton(R.string.result_animal_quiz, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myAnimalQuizFragment.resetAnimalQuiz();
}
});
return builder.create();
}
}
The problem is in this line.Remove the line below from your code
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
You never ever create an Activity's instance with new operator. Its android Component class it initializes automatically with Intent . All Activities in android must go through a lifecycle so that they have a valid context attached to them. Read Activity.
The solution for this problem.
if(getActivity()!=null){
((MainActivity)getActivity()).showDialog()
}
For your new problem which you mentioned in comments.
You never assign myAnimalQuizFragment so it will give you NullPointerException anyway . Access it from your MainActivity.
((MainActivity)getActivity()).myAnimalQuizFragment.resetAnimalQuiz();
Make myAnimalQuizFragment as public in MainActivity.
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);
}
I'm a just a beginner to android & java. I'm trying to build an app that will tell you if you win or lose base on the Martingale on gambling.
My concept is, you can set your money, target and the minimum bet.
for example is if I set my current money is 1000, and my target is to get 1100, and the minimum bet is 100, the app will auto run the function for example 10 times and calculate the win rate.
now I'm stucked, the android studio shows no error, however, whenever i try to emulate the app, it show "unfortunately, app has stopped" everything seem just fine to me, i don't know how to find the error... please guide me. million thanks
package com.example.android.gambling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
public void seeRate(View view) {
TextView textview = (TextView)findViewById(R.id.textView);
textview.setText("You " + winPercentage());
}
public boolean calRate(double currentMoney, double theTarget, double minBet) {
while (currentMoney>minBet){
boolean win = winRate();
if (win){
currentMoney += minBet;
minBet = minBet;
}
else {
currentMoney -= minBet;
minBet *= 2;
}
if (currentMoney>=theTarget){
return true;
}
}
return false;
}
private boolean winRate() {
double d = Math.random();
if (d < 0.5)
return true;
else
return false;
}
public int winPercentage (){
int numberWin = 0;
for (int i=0; i<=10; i++){
boolean win = calRate(currentMoney, theTarget, minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin/10*100;
}
}
Edit(1)
package com.example.android.gambling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void seeRate(View view) {
TextView textview = (TextView)findViewById(R.id.textView);
textview.setText("You " + winPercentage());
}
public boolean calRate(double currentMoney, double theTarget, double minBet) {
while (currentMoney>minBet){
boolean win = winRate();
if (win){
currentMoney += minBet;
minBet = minBet;
}
else {
currentMoney -= minBet;
minBet *= 2;
}
if (currentMoney>=theTarget){
return true;
}
}
return false;
}
private boolean winRate() {
double d = Math.random();
if (d < 0.5)
return true;
else
return false;
}
public int winPercentage (){
int numberWin = 0;
for (int i=0; i<=10; i++){
boolean win = calRate(currentMoney, theTarget, minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin/10*100;
}
}
Do this:
private EditText cMoney;
private double currentMoney;
private EditText target;
private double theTarget;
private EditText bet;
private double minBet;
private boolean findRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cMoney = (EditText) findViewById(R.id.money);
currentMoney = Double.parseDouble(cMoney.getText().toString());
target = (EditText) findViewById(R.id.target);
theTarget = Double.parseDouble(target.getText().toString());
bet = (EditText) findViewById(R.id.bet);
minBet = Double.parseDouble(bet.getText().toString());
findRate = calRate(currentMoney, theTarget, minBet);
}
You can't put the code like this outside of any method/constructor, unless it's static/initializer block and there's definitely no reason to use them here.
Also, I see that your parameter name in calRate is currentMoney same as your variable, try to avoid this, it may be confusing for someone else reading your code, for you and maybe even for compiler if you go too far.
Put this:
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
Inside brackets of method onCreate() and then export variables theTarget, minBet, findRate and currentMoney into fields so that they can be visible in other parts of this class.
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