For Loop not waiting for user input - java

Hello i have an android project ongoing at the moment. The user must answer a maths question then point should be awarded/taken away for the answer then the code should display a second different question until 10 questions have been completed. The problem is that the code skips the loop and instantly finishes the game. I have attempted using a while loop but the same problem happened. I thought about an if but couldn't work out how to re run the if. Below is the whole code of the project but the main problem is the for loop.
package com.example.mixmathsv3;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class SimpleModeActivity extends AppCompatActivity {
Button checkButt, nextQuestionButt;
TextView resultText, simpleQuestionText, scoreText, questionNumberText;
EditText userAnswer;
public volatile int completedTimes = 0;
public int scoreValue = 0;
public int intUserAnswer = 0;
public String questionAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_mode);
resultText = (TextView) findViewById(R.id.result);
checkButt = (Button) findViewById(R.id.checkButt);
simpleQuestionText = (TextView) findViewById(R.id.simpleQuestionText);
scoreText = (TextView) findViewById(R.id.scoreText);
userAnswer = (EditText) findViewById(R.id.userAnswer);
//nextQuestionButt = (Button) findViewById(R.id.nextQuestion/Butt);
//questionNumberText = (TextView) findViewById(R.id.questionNumberText);
final String[] questionArray = {"5+2", "10+3", "7+1", "9+0", "1+6"};
final String[] answerArray = {"7", "13", "8", "9", "7"};
final Random r = new Random();
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
for (int i = 1; i < 11; i++) {
//System.out.println(i);
//Toast.makeText(getApplicationContext(), ("loop successful"), Toast.LENGTH_SHORT).show();
checkButt.setEnabled(true);
checkButt.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View v) {
checkButt.setEnabled(false);
intUserAnswer = Integer.parseInt(userAnswer.getText().toString());
int intQuestionAnswer = Integer.parseInt(questionAnswer);
if (intUserAnswer == intQuestionAnswer) {
resultText.setText("Correct");
scoreValue = scoreValue + 10;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes);
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
if (intUserAnswer != intQuestionAnswer) {
resultText.setText("Incorrect");
scoreValue = scoreValue - 5;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes)
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
}
});
}
Toast.makeText(getApplicationContext(), ("Game Over"), Toast.LENGTH_SHORT).show();

setOnClickListener does not do what you think :
setOnClickListener is used to register a method that will be called only if the user click on the button.
In your example, the for-loop register 10 times a new onClickListener which is not what we want.
In your case, you must not use the for-loop which is executed instantly. Change the question and the text when the user clicked on the button.
final String[] questionArray = {"5+2", "10+3", "7+1", "9+0", "1+6"};
final String[] answerArray = {"7", "13", "8", "9", "7"};
final Random r = new Random();
int answered = 0;
// Initial question
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
checkButt.setEnabled(true);
checkButt.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View v) {
checkButt.setEnabled(false);
intUserAnswer = Integer.parseInt(userAnswer.getText().toString());
int intQuestionAnswer = Integer.parseInt(questionAnswer);
if (intUserAnswer == intQuestionAnswer) {
resultText.setText("Correct");
scoreValue = scoreValue + 10;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes);
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
if (intUserAnswer != intQuestionAnswer) {
resultText.setText("Incorrect");
scoreValue = scoreValue - 5;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes)
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
answered++;// We update the count of answered question
if(answered == 10) {
// Finish
Toast.makeText(getApplicationContext(), ("Game Over"), Toast.LENGTH_SHORT).show();
} else {
// Change question
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
}
}
});
I suggest you to learn more about how Android is working and callback methods.

You don't need to put everything in the loop. Move all logic outside the loop and it should work.

Related

CountDownTimer for quiz can't be accessed how I need it to be

I am writing a small math's quiz with 10 questions per level. I'm trying to write a 10 second timer which has the following functions:
Moves to the next question when it runs out and restarts the timer
Restarts when a question is entered
My issue is that regardless of how I write this code, I cannot access the timer from both the "onFinish()" function as well as the rest of the program. such as "onCorrect()" I need to be able to cancel and restart an existing timer initialised in "onCreate()" however I can't then access that timer through a MyCountDownTimer class or function (I've tried using both to no avail.)
My code is below with comments to show where I need the timers to work.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class Level2 extends AppCompatActivity {
int score = 0;
int q = 1;
TextView value;
TextView q_num;
TextView timer_label = findViewById(R.id.Timer);
/*public class MyCountDownTimer extends CountDownTimer {
TextView timer_label = findViewById(R.id.Timer);
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
onDone();
}
#Override
public void onTick(long millisUntilFinished) {
int temp = (int)millisUntilFinished/1000;
//do what ever You want
timer_label.setText(String.format(getResources().getString(R.string.timer_string),String.valueOf(temp)));
}
}
#Override
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level2);
q = 1;
//MyCountDownTimer t = new MyCountDownTimer(11000,1000);
Button b1 = findViewById(R.id.option1);
Button b2 = findViewById(R.id.option2);
Button b3 = findViewById(R.id.option3);
Button b4 = findViewById(R.id.option4);
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
//
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
getSupportActionBar().setCustomView(R.layout.action_layout);
//Gives action bar style
value = findViewById(R.id.score_value);
q_num = findViewById(R.id.question_number);
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b1.getText();
onCheck(ans,score);
}
});
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b2.getText();
onCheck(ans,score);
}
});
b3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b3.getText();
onCheck(ans,score);
}
});
b4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b4.getText();
onCheck(ans,score);
}
});
}
public void onCheck(String ans, int score) {
TextView ans_data = findViewById(R.id.answer_data);
String correct = (String) ans_data.getText();
if (ans.contains(correct)) {
onCorrect(score);
}
else{
onWrong();
}
}
public void onCorrect(int temp){
//t.cancel()
//t.start()
temp++;
score = temp;
q++;
if(q >= 11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
value.setText(String.valueOf(score));
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
public void onDone(){
//t.start()
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
}
public void onWrong(){
//t.cancel()
//t.start
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
For reference;
onCheck() checks if the answer is right
onCorrect() is right
onWrong() is wrong
onDone() is when the timer runs out
The root of my issue is that I cannot put t into onDone as it's called by the MyCountDownTimer class which doesn't have access to the t called in onCreate.
Declare MyCountDownTimer t outside of onCreate() as a global variable.

My Tic Tac Toe game thinks there's a winner whenever there's any 3 symbols in a row. How can I fix this?

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

How do I call a function from within a statement in the event listener?

I've been working on a little project, and I had a problem in implementing my idea. The app I'm trying to build is an educational app that gives random basic math (+,-,*,/) question, if the student got it right, it should show the next question, otherwise, it should give him/her another chance to try again.
My problem falls specifically in the last part, I wrote a function to show the next question, but I don't exactly know how to call it when the button is clicked.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import java.util.Random;
import static java.lang.String.valueOf;
public class MainActivity extends AppCompatActivity {
TextView fN;
TextView sN;
TextView oP;
TextView out;
TextView ht;
EditText ans;
Button btn;
int answer;
int fNum;
int sNum;
int opNum;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ht.setVisibility(View.GONE);
final String[] ops = {"+","-","÷","×"};
final String[] pass = {
"Very good!",
"Excellent!",
"Nice work!",
"Keep up the good work!"
};
final String[] fail = {
"No. Please try again.",
"Wrong. Try once more.",
"Don't give up!",
"No. Keep trying."
};
public static void nextQ() {
//UI variables
fN = findViewById(R.id.fN);
sN = findViewById(R.id.sN);
oP = findViewById(R.id.oP);
out = findViewById(R.id.out);
ans = findViewById(R.id.Ans);
btn = findViewById(R.id.btn);
//functionalities variables
r = new Random();
fNum = r.nextInt(9);
sNum = r.nextInt(9);
opNum = r.nextInt(ops.length);
if (opNum == 0)
answer = fNum + sNum;
if (opNum == 1)
answer = fNum - sNum;
if (opNum == 2)
answer = fNum / sNum;
if (opNum == 3)
answer = fNum * sNum;
ht.setText(answer);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ht = findViewById(R.id.hText);
fN.setText(fNum);
sN.setText(sNum);
oP.setText(ops[opNum]);
int usrAns = Integer.parseInt(valueOf(ans.getText()));
int rMSG = r.nextInt(pass.length);
if(answer == usrAns)
out.setText(""+pass[rMSG]);
nextQ();
if(answer != usrAns)
out.setText(""+fail[rMSG]);
}
});
}
}
Try to put this code & check whether it works or not?
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import static java.lang.String.valueOf;
public class MainActivity extends AppCompatActivity {
TextView fN;
TextView sN;
TextView oP;
TextView out;
TextView ht;
EditText ans;
Button btn;
int answer;
int fNum;
int sNum;
int opNum;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ht.setVisibility(View.GONE);
btn = findViewById(R.id.btn);
fN = findViewById(R.id.fN);
sN = findViewById(R.id.sN);
oP = findViewById(R.id.oP);
out = findViewById(R.id.out);
ans = findViewById(R.id.Ans);
final String[] ops = {"+", "-", "÷", "×"};
final String[] pass = {
"Very good!",
"Excellent!",
"Nice work!",
"Keep up the good work!"
};
final String[] fail = {
"No. Please try again.",
"Wrong. Try once more.",
"Don't give up!",
"No. Keep trying."
};
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ht = findViewById(R.id.hText);
fN.setText(fNum);
sN.setText(sNum);
oP.setText(ops[opNum]);
int usrAns = Integer.parseInt(valueOf(ans.getText()));
int rMSG = r.nextInt(pass.length);
if (answer == usrAns)
out.setText("" + pass[rMSG]);
nextQ();
if (answer != usrAns)
out.setText("" + fail[rMSG]);
}
});
}
public void nextQ() {
//functionalities variables
r = new Random();
fNum = r.nextInt(9);
sNum = r.nextInt(9);
opNum = r.nextInt(ops.length);
if (opNum == 0)
answer = fNum + sNum;
if (opNum == 1)
answer = fNum - sNum;
if (opNum == 2)
answer = fNum / sNum;
if (opNum == 3)
answer = fNum * sNum;
ht.setText(answer);
}
}
Remove static from function nextQ(). And also remove it from onCreate(). put it outside on onCreate().
Function will look like:
onCreate(){ ... }
public void nextQ() {
....
}
Call it like
MainActivity.this.nextQ();
Remove below code form nextQ() and put in onCreate() method:
fN = findViewById(R.id.fN);
sN = findViewById(R.id.sN);
oP = findViewById(R.id.oP);
out = findViewById(R.id.out);
ans = findViewById(R.id.Ans);
btn = findViewById(R.id.btn);

Dialog Fragment does not working?

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.

Android: pass variables to/out button anonymous class

package com.example.rami.androidstudio_312332604_guessgame;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
private String changeCharInPosition(int position, char ch, String str) {
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
private void start() {
TextView errortext = (TextView) findViewById(R.id.statustext);
Button button = (Button) findViewById(R.id.guessbt);
TextView tv = (TextView) findViewById(R.id.guessingtext);//get the textview from the activity
TextView testtext = (TextView) findViewById(R.id.testtext);//get the testview from the activity
EditText edittext = (EditText) findViewById(R.id.editText);
String[] world = getResources().getStringArray(R.array.words);// get the array from string xml
Random rand = new Random();
errortext.setText("");
int randomNum = rand.nextInt(world.length);
String country = world[randomNum];
String s = "";
for (int i = 0; i < country.length(); i++) {
if (country.charAt(i) != ' ')
s += '?';
else
s += ' ';
}
tv.setText(s);
testtext.setText(world[randomNum]);
button.setEnabled(true);
//Toast toast = Toast.makeText(getApplicationContext(), points, Toast.LENGTH_LONG);
//toast.show();
}
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start();
Button button = (Button) findViewById(R.id.guessbt);
button.setOnClickListener(new View.OnClickListener() {
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
private void clear() {
ImageView img = (ImageView) findViewById(R.id.errorimg);
TextView errortext = (TextView) findViewById(R.id.statustext);
img.setImageResource(R.mipmap.error_num0);
counter = 6;
lettersguessed.clear();
errortext.setText("");
}
public void onClick(View v) {
EditText guessedtext = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.guessbt);
TextView questionstext = (TextView) findViewById(R.id.guessingtext);
TextView errortext = (TextView) findViewById(R.id.statustext);
if (guessedtext.getText().length() != 1) {//to make sure it's one char
Toast toast = Toast.makeText(getApplicationContext(), "Please Enter One Char", Toast.LENGTH_SHORT);
toast.show();
guessedtext.setText("");
return;
}
String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
char uc = Character.toUpperCase(guessedtext.getText().charAt(0));
char lc = Character.toLowerCase(guessedtext.getText().charAt(0));
guessedtext.setText("");
if (lettersguessed.contains(uc)) {
Toast toast = Toast.makeText(getApplicationContext(), "You tried that before", Toast.LENGTH_SHORT);
toast.show();
return;
}
lettersguessed.add(uc);
boolean right = false;
for (int i = 0; i < country.length(); i++) {
char cc = country.charAt(i);
if (cc == uc || cc == lc) {
right = true;
questionstext.setText(changeCharInPosition(i, cc, questionstext.getText().toString()));
errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
}
}
if (!right) {
if (counter == 1) {
Toast toast = Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_SHORT);
toast.show();
clear();
//points=-20;
return;
}
ImageView img = (ImageView) findViewById(R.id.errorimg);
counter--;
img.setImageResource(R.mipmap.error_num1);
errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
}
if (questionstext.getText().toString().indexOf('?') < 0) {
Toast toast = Toast.makeText(getApplicationContext(), "Done it!", Toast.LENGTH_SHORT);
toast.show();
button.setEnabled(false);
clear();
//points += 20;
return;
}
}
});
Button newtb = (Button) findViewById(R.id.newbt);
newtb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
start();
}
});
Button giveupbt = (Button) findViewById(R.id.giveupbt);
giveupbt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button button = (Button) findViewById(R.id.guessbt);
String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
TextView guessedtext = (TextView) findViewById(R.id.guessingtext);
guessedtext.setText(country);
button.setEnabled(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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
**These two variables, I want to reach or to make this class vars and reach them from the anonymous class. Because I want to read this and change their value
More info: the button is the guessing button for guessing countries names game and after entering the char into edittext you click this button to make your guess.
Any Ideas?
Just make these two variables as final and then access them in your inner class.
So it then becomes,
final ArrayList<Character> lettersguessed = new ArrayList<Character>();
final int[] counter = new int[1];
counter[0] = 6;
just replace counter by counter[0].

Categories