I'm making a tictactoe app where corresponding messages reflect whose (Player X or Player Y) turn it is and who wins. This worked with no issues. Then I added a feature using Preferences and Fragments, where the user could add specific names to Player X and Player Y and the messages would implement their names. However, now everytime I open the app it remembers a previous session of the game. I think it loads the game as it was the previous time it was paused. How can I get it to load a new game everytime the emulator opens?
I'm sure it's something simple, I'm just new to AndroidStudio and I'm out of ideas. Thank you!
This is my Activity code
package com.asebastian.tictactoe;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TictactoeActivity extends Activity implements OnClickListener {
private Button btn1;
private Button btn2;
private Button btn3;
private Button btn4;
private Button btn5;
private Button btn6;
private Button btn7;
private Button btn8;
private Button btn9;
private TextView txtmsg;
private int r = 0;
private String btn1txt = " ";
private String btn2txt = " ";
private String btn3txt = " ";
private String btn4txt = " ";
private String btn5txt = " ";
private String btn6txt = " ";
private String btn7txt = " ";
private String btn8txt = " ";
private String btn9txt = " ";
private String Xname = " ";
private String Yname = " ";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tictactoe);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
txtmsg = (TextView)findViewById(R.id.txtMessage);
txtmsg.setText("Player X's turn");
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.tictactoe,menu);
return true;
}
#Override
public void onPause(){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("btn1txt",btn1.getText().toString());
editor.putString("btn2txt",btn2.getText().toString());
editor.putString("btn3txt",btn3.getText().toString());
editor.putString("btn4txt",btn4.getText().toString());
editor.putString("btn5txt",btn5.getText().toString());
editor.putString("btn6txt",btn6.getText().toString());
editor.putString("btn7txt",btn7.getText().toString());
editor.putString("btn8txt",btn8.getText().toString());
editor.putString("btn9txt",btn9.getText().toString());
editor.putInt("r",r);
editor.commit();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
btn1.setText(prefs.getString("btn1txt",""));
btn2.setText(prefs.getString("btn2txt",""));
btn3.setText(prefs.getString("btn3txt",""));
btn4.setText(prefs.getString("btn4txt",""));
btn5.setText(prefs.getString("btn5txt",""));
btn6.setText(prefs.getString("btn6txt",""));
btn7.setText(prefs.getString("btn7txt",""));
btn8.setText(prefs.getString("btn8txt",""));
btn9.setText(prefs.getString("btn9txt",""));
Xname = prefs.getString("pref_edittextX","");
Yname = prefs.getString("pref_edittextY","");
txtmsg.setText(Xname + "'s turn");
r = prefs.getInt("r",0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.new_game){
btn1.setEnabled(true);
btn2.setEnabled(true);
btn3.setEnabled(true);
btn4.setEnabled(true);
btn5.setEnabled(true);
btn6.setEnabled(true);
btn7.setEnabled(true);
btn8.setEnabled(true);
btn9.setEnabled(true);
btn1.setText("");
btn2.setText("");
btn3.setText("");
btn4.setText("");
btn5.setText("");
btn6.setText("");
btn7.setText("");
btn8.setText("");
btn9.setText("");
r = 0;
txtmsg.setText("Player X's turn");
}
else if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn1) {
r++;
if ((r % 2) == 0) {
btn1.setText("O");
} else {
btn1.setText("X");
}
}
if (v.getId() == R.id.btn2) {
r++;
if ((r % 2) == 0) {
btn2.setText("O");
} else {
btn2.setText("X");
}
}
if (v.getId() == R.id.btn3) {
r++;
if ((r % 2) == 0) {
btn3.setText("O");
} else {
btn3.setText("X");
}
}
if (v.getId() == R.id.btn4) {
r++;
if ((r % 2) == 0) {
btn4.setText("O");
} else {
btn4.setText("X");
}
}
if (v.getId() == R.id.btn5) {
r++;
if ((r % 2) == 0) {
btn5.setText("O");
} else {
btn5.setText("X");
}
}
if (v.getId() == R.id.btn6) {
r++;
if ((r % 2) == 0) {
btn6.setText("O");
} else {
btn6.setText("X");
}
}
if (v.getId() == R.id.btn7) {
r++;
if ((r % 2) == 0) {
btn7.setText("O");
} else {
btn7.setText("X");
}
}
if (v.getId() == R.id.btn8) {
r++;
if ((r % 2) == 0) {
btn8.setText("O");
} else {
btn8.setText("X");
}
}
if (v.getId() == R.id.btn9) {
r++;
if ((r % 2) == 0) {
btn9.setText("O");
} else {
btn9.setText("X");
}
}
if (Xname.isEmpty() && Yname.isEmpty()) {
if ((r % 2) == 0) {
txtmsg.setText("Player X's turn");
} else {
txtmsg.setText("Player Y's turn");
}
} else {
if ((r % 2) == 0) {
txtmsg.setText(Xname + "'s turn");
} else {
txtmsg.setText(Yname + "'s turn");
}
}
btn1txt = btn1.getText().toString();
btn2txt = btn2.getText().toString();
btn3txt = btn3.getText().toString();
btn4txt = btn4.getText().toString();
btn5txt = btn5.getText().toString();
btn6txt = btn6.getText().toString();
btn7txt = btn7.getText().toString();
btn8txt = btn8.getText().toString();
btn9txt = btn9.getText().toString();
calcWinner();
}
public void calcWinner() {
if (btn1txt == "X" && btn2txt == "X" && btn3txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn2txt == "O" && btn3txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn4txt == "X" && btn5txt == "X" && btn6txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn4txt == "O" && btn5txt == "O" && btn6txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn7txt == "X" && btn8txt == "X" && btn8txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn7txt == "O" && btn8txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn1txt == "X" && btn4txt == "X" && btn7txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn4txt == "O" && btn7txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn2txt == "X" && btn5txt == "X" && btn8txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn2txt == "O" && btn5txt == "O" && btn8txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn3txt == "X" && btn6txt == "X" && btn9txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn3txt == "O" && btn6txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn1txt == "X" && btn5txt == "X" && btn9txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn5txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn3txt == "X" && btn5txt == "X" && btn7txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn3txt == "O" && btn5txt == "O" && btn7txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (r == 9) {
txtmsg.setText("Tie Game!");
disableButtons();
}
}
public void disableButtons(){
btn1.setEnabled(false);
btn2.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
btn5.setEnabled(false);
btn6.setEnabled(false);
btn7.setEnabled(false);
btn8.setEnabled(false);
btn9.setEnabled(false);
}
}
This is my Fragment code:
package com.asebastian.tictactoe;
import android.os.Bundle;
import android.preference.PreferenceFragment;
/**
* A simple {#link Fragment} subclass.
*/
public class SettingsFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
This is the code to add the Fragment:
package com.asebastian.tictactoe;
import android.app.Activity;
import android.os.Bundle;
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,new
SettingsFragment()).commit();
}
}
So i guess by Storing/Restoring to/from SharedPreferences that you are trying to save the state of the activity!
And that is wrong (unless you deleted the SharedPreferences saved content in onDestroy()) becuase every time you open the app again the on onResume() will be called and hence state will be restored from SharedPreferences.
See The Activity Lifecycle
So, The solution is not to use SharedPreferences to save/restore activity state but instead override the methods onSaveInstanceState & onRestoreInstanceState like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString("btn1txt",btn1.getText().toString());
// and So on
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
btn1.setText(savedInstanceState.getString("btn1txt"));
// and so on
}
Note:
The system calls onRestoreInstanceState() after the onStart()method.
Also The system calls onRestoreInstanceState() only if there is a saved state to restore.
See Saving and restoring activity state
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wrote a code for tictactoe game, however it it showing me this error at run time:
Exception: Unable to instantiate activity ComponentInfo{com.tictactoe.ajaykulkarni.tictactoe/com.tictactoe.ajaykulkarni.tictactoe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
My MainActivity is:
package com.tictactoe.ajaykulkarni.tictactoe;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//protected DrawerLayout mdrawerLayout;
/*Game plan*/
private TicTacToeGame mGame;
// Buttons making up the board
private Button mBoardButtons[];
private Button mNewGame;
// Various text displayed
private TextView mInfoTextView;
private TextView mPlayerOneCount;
private TextView mTieCount;
private TextView mPlayerTwoCount;
private TextView mPlayerOneText;
private TextView mPlayerTwoText;
private int mPlayerOneCounter = 0;
private int mTieCounter = 0;
private int mPlayerTwoCounter = 0;
private boolean mPlayerOneFirst = true;
private boolean mIsSinglePlayer = false;
private boolean mIsPlayerOneTurn = true;
private boolean mGameOver = false;
boolean mGameType = getIntent().getExtras().getBoolean("gameType");
private Button[] getmBoardButtons() {
mBoardButtons = new Button[mGame.getBOARD_SIZE()];
mBoardButtons[0] = (Button) findViewById(R.id.one);
mBoardButtons[1] = (Button) findViewById(R.id.two);
mBoardButtons[2] = (Button) findViewById(R.id.three);
mBoardButtons[3] = (Button) findViewById(R.id.four);
mBoardButtons[4] = (Button) findViewById(R.id.five);
mBoardButtons[5] = (Button) findViewById(R.id.six);
mBoardButtons[6] = (Button) findViewById(R.id.seven);
mBoardButtons[7] = (Button) findViewById(R.id.eight);
mBoardButtons[8] = (Button) findViewById(R.id.nine);
addListenerOnButton();
// setup the textviews
mInfoTextView = (TextView) findViewById(R.id.information);
mPlayerOneCount = (TextView) findViewById(R.id.humanCount);
mTieCount = (TextView) findViewById(R.id.tiesCount);
mPlayerTwoCount = (TextView) findViewById(R.id.androidCount);
mPlayerOneText = (TextView) findViewById(R.id.human);
mPlayerTwoText = (TextView) findViewById(R.id.android);
// set the initial counter display values
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
// create a new game object
mGame = new TicTacToeGame();
// start a new game
startNewGame(mGameType);
return mBoardButtons;
}
//mBoardButtons = new Button[mGame.getBOARD_SIZE()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.play) {
Log.d("DEBUG", "Play option selected!");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
} else if (id == R.id.exit) {
Log.d("DEBUG", "Exit option selected!");
MainActivity.this.finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void addListenerOnButton(){
mNewGame = (Button) findViewById(R.id.NewGame);
mNewGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startNewGame(mIsSinglePlayer);
}
});
}
// start a new game
// clears the board and resets all buttons / text
// sets game over to be false
private void startNewGame(boolean isSingle)
{
this.mIsSinglePlayer = isSingle;
mGame.clearBoard();
for (int i = 0; i < mBoardButtons.length; i++)
{
mBoardButtons[i].setText("");
mBoardButtons[i].setEnabled(true);
mBoardButtons[i].setOnClickListener(new ButtonClickListener(i));
///mBoardButtons[i].setBackgroundDrawable(getResources().getDrawable(R.drawable.blank));
}
if (mIsSinglePlayer)
{
mPlayerOneText.setText("User:");
mPlayerTwoText.setText("Android:");
if (mPlayerOneFirst)
{
mInfoTextView.setText(R.string.first_human);
mPlayerOneFirst = false;
}
else
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
mPlayerOneFirst = true;
}
}
mGameOver = false;
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
public void onClick(View view)
{
if (!mGameOver)
{
if (mBoardButtons[location].isEnabled())
{
if (mIsSinglePlayer)
{
setMove(mGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
winner = mGame.checkForWinner();
}
if (winner == 0)
mInfoTextView.setText(R.string.turn_human);
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner == 2)
{
mInfoTextView.setText(R.string.result_human_wins);
mPlayerOneCounter++;
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mGameOver = true;
}
else
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayerTwoCounter++;
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
mGameOver = true;
}
}
else
{
if (mIsPlayerOneTurn)
setMove(mGame.PLAYER_ONE, location);
else
setMove(mGame.PLAYER_TWO, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
if (mIsPlayerOneTurn)
{
mInfoTextView.setText(R.string.turn_player_two);
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_one);
mIsPlayerOneTurn = true;
}
}
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner == 2)
{
mInfoTextView.setText(R.string.result_player_one_wins);
mPlayerOneCounter++;
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mGameOver = true;
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.result_player_two_wins);
mPlayerTwoCounter++;
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
mGameOver = true;
mIsPlayerOneTurn = true;
}
}
}
}
}
}
// set move for the current player
private void setMove(char player, int location)
{
mGame.setMove(player, location);
mBoardButtons[location].setEnabled(false);
if (player == mGame.PLAYER_ONE)
mBoardButtons[location].setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_x));
else
mBoardButtons[location].setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_o));
}
}
and TicTacToeGame.class is:
package com.tictactoe.ajaykulkarni.tictactoe;
/**
* Created by Ajay Kulkarni-enEXL on 02/16/2017.
*/
import java.util.Random;
public class TicTacToeGame {
private char mBoard[];
private final static int BOARD_SIZE = 9;
public static final char PLAYER_ONE = 'X';
public static final char PLAYER_TWO = '0';
public static final char EMPTY_SPACE = ' ';
private Random mRand;
public static int getBOARD_SIZE() {
// Return the size of the board
return BOARD_SIZE;
}
public TicTacToeGame(){
mBoard = new char[BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
mBoard[i] = EMPTY_SPACE;
mRand = new Random();
}
// Clear the board of all X's and O's
public void clearBoard()
{
for (int i = 0; i < BOARD_SIZE; i++)
{
mBoard[i] = EMPTY_SPACE;
}
}
// set the given player at the given location on the game board.
// the location must be available, or the board will not be changed.
public void setMove(char player, int location)
{
mBoard[location] = player;
}
// Return the best move for the computer to make. You must call setMove()
// to actually make the computer move to that location.
public int getComputerMove()
{
int move;
// First see if there's a move O can make to win
for (int i = 0; i < getBOARD_SIZE(); i++)
{
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
{
char curr = mBoard[i];
mBoard[i] = PLAYER_TWO;
if (checkForWinner() == 3)
{
setMove(PLAYER_TWO, i);
return i;
}
else
mBoard[i] = curr;
}
}
// See if there's a move O can make to block X from winning
for (int i = 0; i < getBOARD_SIZE(); i++)
{
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
{
char curr = mBoard[i];
mBoard[i] = PLAYER_ONE;
if (checkForWinner() == 2)
{
setMove(PLAYER_TWO, i);
return i;
}
else
mBoard[i] = curr;
}
}
// Generate random move
do
{
move = mRand.nextInt(getBOARD_SIZE());
} while (mBoard[move] == PLAYER_ONE || mBoard[move] == PLAYER_TWO);
setMove(PLAYER_TWO, move);
return move;
}
// Check for a winner and return a status value indicating who has won.
// Return 0 if no winner or tie yet, 1 if it's a tie, 2 if X won, or 3
// if O won.
public int checkForWinner()
{
// Check horizontal wins
for (int i = 0; i <= 6; i += 3)
{
if (mBoard[i] == PLAYER_ONE &&
mBoard[i+1] == PLAYER_ONE &&
mBoard[i+2] == PLAYER_ONE)
return 2;
if (mBoard[i] == PLAYER_TWO &&
mBoard[i+1] == PLAYER_TWO &&
mBoard[i+2] == PLAYER_TWO)
return 3;
}
// Check vertical wins
for (int i = 0; i <= 2; i++)
{
if (mBoard[i] == PLAYER_ONE &&
mBoard[i+3] == PLAYER_ONE &&
mBoard[i+6] == PLAYER_ONE)
return 2;
if (mBoard[i] == PLAYER_TWO &&
mBoard[i+3] == PLAYER_TWO &&
mBoard[i+6] == PLAYER_TWO)
return 3;
}
// Check for diagonal wins
if ((mBoard[0] == PLAYER_ONE &&
mBoard[4] == PLAYER_ONE &&
mBoard[8] == PLAYER_ONE) ||
mBoard[2] == PLAYER_ONE &&
mBoard[4] == PLAYER_ONE &&
mBoard[6] == PLAYER_ONE)
return 2;
if ((mBoard[0] == PLAYER_TWO &&
mBoard[4] == PLAYER_TWO &&
mBoard[8] == PLAYER_TWO) ||
mBoard[2] == PLAYER_TWO &&
mBoard[4] == PLAYER_TWO &&
mBoard[6] == PLAYER_TWO)
return 3;
// Check for a tie
for (int i = 0; i < getBOARD_SIZE(); i++)
{
// if we find a number, then no one has won yet
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
return 0;
}
// If we make it through the previous loop, all places are taken, so it's a tie
return 1;
}
}
How can I fix that error?
You are trying to get extras from a field in the Activity, i.e. you are trying to get the extras before the Activity is created. If you get the extras from the onCreate method, it won't be a null value.
Example:
boolean mGameType;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGameType = getIntent().getExtras().getBoolean("gameType");
...
}
EDIT: If you want to send extra from one Activity to another, you should start it this way:
startActivity(new Intent(SenderActivity.this, MainActivity.class)
.putExtra("gameType", true));
Hi I need some help to create a function can fill an EditText by the first Letter and the first Vowel of another EditText.
Something like this:
EditText = Jhon
Output = JO
I have this but still not working;
public class MainActivity extends Activity {
private EditText Result;
private EditText MyName;
private EditText showResult;
private String MyVowel;
private String cadena, PartOne;
private int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Result = (TextView) findViewById(R.id.showResult);
MyName= (EditText)findViewById(R.id.NameInput);
getInfo = (Button)findViewById(R.id.getInfoButton);
getInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inputText = myName.getText().toString();
String partOne= inputText.substring(0,1);
for(int i=0;i <inputText.length();i++){
if((inputText.charAt(i) == 'a') ||
(inputText.charAt(i) == 'e') ||
(inputText.charAt(i) == 'i') ||
(inputText.charAt(i) == 'o') ||
(inputText.charAt(i) == 'u')) {
System.out.println(cadena);
}
}
showResult.setText(PartOne);
}
});
}
}
You havn't said what your issue is. If you are stuck at the logic see the below code,
private String getShortForm(String inputText){
List<Character> vowels = new ArrayList<Character>() {
{
add('a');
add('e');
add('i');
add('o');
add('u');
add('A');
add('E');
add('I');
add('O');
add('U');
}
};
String partOne = inputText.substring(0, 1);
for (int i = 0; i < inputText.length(); i++) {
char c = inputText.charAt(i);
if(vowels.contains(c)){
partOne += c;
break;
}
}
return partOne.toUpperCase();
}
Usage inside onClick,
Result.setText(getShortForm(inputText));
Here's the solution
public class MainActivity extends AppCompatActivity{
private TextView Result;
private EditText MyName;
private Button getInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Result = (TextView) findViewById(R.id.showResult);
MyName= (EditText)findViewById(txtText);
getInfo = (Button)findViewById(btnSpeak);
getInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputText = MyName.getText().toString();
String partOne= inputText.substring(0,1);
Log.e("inputText: "+inputText, "part one: "+partOne);
String vowels = "";
for(int i=0;i <inputText.length();i++){
if((inputText.charAt(i) == 'a') ||
(inputText.charAt(i) == 'e') ||
(inputText.charAt(i) == 'i') ||
(inputText.charAt(i) == 'o') ||
(inputText.charAt(i) == 'u') ||
(inputText.charAt(i) == 'A') ||
(inputText.charAt(i) == 'E') ||
(inputText.charAt(i) == 'I') ||
(inputText.charAt(i) == 'O') ||
(inputText.charAt(i) == 'U')){
vowels = vowels+inputText.charAt(i);
}
}
Log.e("inputText: "+inputText, "vowelsFinal: "+vowels);
String partTwo = vowels.substring(0,1);
Log.e("inputText: "+inputText, "partTwo: "+partTwo);
String finalString = partOne+partTwo;
Log.e("inputText: "+inputText, "finalString: "+finalString);
Result.setText(finalString);
}
});
}
}
Hope this solves your issue :)
Hey guys so I have 3 imageButton icons/tags I want to set. So I do a loop and go through them. Now the user can press a number of tags (such as a food tag, retail tag, housing tag, etc) and that adds to a Global ArrayList. Now if the user only pressed 1 tag and there's three imageButtons that need to be set, I want to set the first imagebutton to the only tag they picked and set the rest to a white blank image, but I keep getting the following error:
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
here is my loop I dunno what I'm doing wrong here.
private void getIcons()
{
iconArray.add(icon1);
iconArray.add(icon2);
iconArray.add(icon3);
for(int i = 0; i < iconArray.size(); i++)
{
ImageView button= iconArray.get(i);
if(Global_Class.getInstance().getValue().tags.size() == 1)
{
if(Global_Class.getInstance().getValue().tags.get(i) == null)//Here is where Its giving me an ERROR!!!!!
{
button.setImageResource(R.drawable.icon_blank);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "food")
{
button.setImageResource(R.drawable.white_small_icon_food);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "bar")
{
button.setImageResource(R.drawable.white_small_icon_bar);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "club")
{
button.setImageResource(R.drawable.white_small_icon_club1);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "housing")
{
button.setImageResource(R.drawable.white_small_icon_housing);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "sports")
{
button.setImageResource(R.drawable.white_small_icon_sports);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "retail")
{
button.setImageResource(R.drawable.white_small_icon_retail);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "outdoors")
{
button.setImageResource(R.drawable.white_small_icon_outdoors1);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "education")
{
button.setImageResource(R.drawable.white_icon_education);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "landmark")
{
button.setImageResource(R.drawable.white_small_icon_landmark);
}
}
else if(Global_Class.getInstance().getValue().tags.size() == 2)
{
if(Global_Class.getInstance().getValue().tags.get(i) == null)
{
button.setImageResource(R.drawable.icon_blank);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "food")
{
button.setImageResource(R.drawable.white_small_icon_food);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "bar")
{
button.setImageResource(R.drawable.white_small_icon_bar);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "club")
{
button.setImageResource(R.drawable.white_small_icon_club1);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "housing")
{
button.setImageResource(R.drawable.white_small_icon_housing);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "sports")
{
button.setImageResource(R.drawable.white_small_icon_sports);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "retail")
{
button.setImageResource(R.drawable.white_small_icon_retail);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "outdoors")
{
button.setImageResource(R.drawable.white_small_icon_outdoors1);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "education")
{
button.setImageResource(R.drawable.white_icon_education);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "landmark")
{
button.setImageResource(R.drawable.white_small_icon_landmark);
}
else
{
//
}
}
else
{
if(Global_Class.getInstance().getValue().tags.get(i) == "food")
{
button.setImageResource(R.drawable.white_small_icon_food);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "bar")
{
button.setImageResource(R.drawable.white_small_icon_bar);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "club")
{
button.setImageResource(R.drawable.white_small_icon_club1);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "housing")
{
button.setImageResource(R.drawable.white_small_icon_housing);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "sports")
{
button.setImageResource(R.drawable.white_small_icon_sports);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "retail")
{
button.setImageResource(R.drawable.white_small_icon_retail);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "outdoors")
{
button.setImageResource(R.drawable.white_small_icon_outdoors1);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "education")
{
button.setImageResource(R.drawable.white_icon_education);
}
else if(Global_Class.getInstance().getValue().tags.get(i) == "landmark")
{
button.setImageResource(R.drawable.white_small_icon_landmark);
}
else
{
//
}
}
}
}
Here is where i make tags arraylist:
public class GlobalVariables
{
public ArrayList<String> tags = new ArrayList<>();
}
And I add to it in another class:
public void onClick(View v)
{
switch (v.getId())
{
case R.id.imageButton:
if(food_pressed)
{
ImageButton food_button = (ImageButton) findViewById(R.id.imageButton);
food_button.setImageResource(R.drawable.pressed_food);
tags.add("food");
food_pressed = false;
break;
}
else
{
ImageButton food_button = (ImageButton) findViewById(R.id.imageButton);
food_button.setImageResource(R.drawable.icon_food);
tags.remove("food");
food_pressed = true;
break;
}
case R.id.imageButton9:
ImageButton done_button = (ImageButton) findViewById(R.id.imageButton9);
done_button.setImageResource(R.drawable.pressed_done);
Global_Class.getInstance().getValue().tags = tags;
//Toast.makeText(getApplicationContext(),Global_Class.getInstance().getValue().tags.toString(),Toast.LENGTH_SHORT).show();
startActivity(toDescription);
break;
etc...
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i am developing android simple calculator it works fine but only one issue when i press 0 again and again it result 00000000 it should be only one 0 my activity file is:
package com.example.droidcalc;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
enter code here
public class MainActivity extends ActionBarActivity {
int first,second,result;
char operation;
EditText disp;
boolean newValue = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
disp = (EditText) findViewById(R.id.editText1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
public void button1(View sender){
if(newValue == true)
disp.setText("1");
else
disp.setText(disp.getText().toString() + "1");
newValue = false;
}
public void button2(View sender){
if(newValue == true)
disp.setText("2");
else
disp.setText(disp.getText().toString() + "2");
newValue = false;
}
public void button3(View sender){
if(newValue == true)
disp.setText("3");
else
disp.setText(disp.getText().toString() + "3");
newValue = false;
}
public void button4(View sender){
if(newValue == true)
disp.setText("4");
else
disp.setText(disp.getText().toString() + "4");
newValue = false;
}
public void button5(View sender){
if(newValue == true)
disp.setText("5");
else
disp.setText(disp.getText().toString() + "5");
newValue = false;
}
public void button6(View sender){
if(newValue == true)
disp.setText("6");
else
disp.setText(disp.getText().toString() + "6");
newValue = false;
}
public void button7(View sender){
if(newValue == true)
disp.setText("7");
else
disp.setText(disp.getText().toString() + "7");
newValue = false;
}
public void button8(View sender){
if(newValue == true)
disp.setText("8");
else
disp.setText(disp.getText().toString() + "8");
newValue = false;
}
public void button9(View sender){
if(newValue == true)
disp.setText("9");
else
disp.setText(disp.getText().toString() + "9");
newValue = false;
}
public void button0(View sender){
/*if(newValue == true)
disp.setText("0");
else
disp.setText(disp.getText().toString() + "0");
newValue = false;*/
disp.append("0");
//newValue = true;
}
public void add(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '+';
newValue=true;
}
public void sub(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '-';
newValue=true;
}
public void mul(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '*';
newValue=true;
}
public void div(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '/';
newValue=true;
}
public void equal(View sender){
second = Integer.parseInt(disp.getText().toString());
switch (operation){
case '+':
result = first + second;
disp.setText(Integer.toString(result));
break;
case '-':
result = first - second;
disp.setText(Integer.toString(result));
break;
case '*':
result = first * second;
disp.setText(Integer.toString(result));
break;
case '/':
result = first / second;
disp.setText(Integer.toString(result));
break;
}
}
public void clr(View sender){
disp.setText("0");
newValue=true;
first = 0;
result = 0;
}
}
You could keep track of what your first number is, and check if it is zero, then do nothing.
if(newValue == true)
disp.setText("0");
else
{
if (!firstNumber.equals("0")
disp.setText(disp.getText().toString() + "0");
newValue = false;
}
Currently, I am making an android app that is going to be a very simple memory game where 1 random button is going to be highlighted, then the user must click the button that was highlighted after the button goes back to normal. If the user gets the button correct the original button that was highlighted the first time will light up, then another random button will light up after just like the first time and they have to click them in order. For further clarification if your unsure its kind of like Simon (The game).
Currently the game is just going to the next random button instead of repeating AND THEN going to a new one and i'm unsure how to change that. Any help would be greatly appreciated!
package com.MakeItMobile.fixmymemory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainScreen extends Activity implements OnClickListener {
Button buttonRed, buttonYellow, buttonOrange, buttonBlack, buttonGreen,
buttonPurple, buttonPink, buttonLime, buttonDarkBlue;
Random randNumber;
List<Integer> whichButton;
int userInput[] = {};
int counter = 0;
int compareCounter = 0;
int n = 0;
Boolean yourTurn = false;
Boolean aiTurn = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
//Getting the buttons
buttonRed = (Button) findViewById(R.id.buttonRed);
buttonYellow = (Button) findViewById(R.id.buttonYellow);
buttonOrange = (Button) findViewById(R.id.buttonOrange);
buttonBlack = (Button) findViewById(R.id.buttonBlack);
buttonGreen = (Button) findViewById(R.id.buttonGreen);
buttonPurple = (Button) findViewById(R.id.buttonPurple);
buttonPink = (Button) findViewById(R.id.buttonPink);
buttonLime = (Button) findViewById(R.id.buttonLime);
buttonDarkBlue = (Button) findViewById(R.id.buttonDarkBlue);
//Setting them clickable
buttonRed.setOnClickListener(this);
buttonYellow.setOnClickListener(this);
buttonOrange.setOnClickListener(this);
buttonBlack.setOnClickListener(this);
buttonGreen.setOnClickListener(this);
buttonPurple.setOnClickListener(this);
buttonPink.setOnClickListener(this);
buttonLime.setOnClickListener(this);
buttonDarkBlue.setOnClickListener(this);
//Giving them a tag for easier comparison in onClick
buttonRed.setTag(1);
buttonYellow.setTag(2);
buttonOrange.setTag(3);
buttonBlack.setTag(4);
buttonGreen.setTag(5);
buttonPurple.setTag(6);
buttonPink.setTag(7);
buttonLime.setTag(8);
buttonDarkBlue.setTag(9);
//Showing a would you like to play dialog
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to begin?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
// Main loop
public void whenStarted() {
if (aiTurn) {
whichButton = new ArrayList<Integer>();
repeatBack();
randomNumber();
n = randomNumber();
if (n == 1) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 2) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 3) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 4) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 5) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 6) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 7) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 8) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 9) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
whichButton.add(n);
yourTurn = true;
} else if (yourTurn) {
}
}
// Repeating back what buttons were clicked each turn
public void repeatBack() {
for (int i = 0; i < whichButton.size(); i++) {
if (whichButton.get(i) == 1) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 2) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 3) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 4) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 5) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 6) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 7) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 8) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 9) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
System.out.println("Which button size and number is "
+ whichButton.size());
System.out.println(i);
}
}
// For repeating back the buttons
// On start this method sets the button to the color and waits 1 second
// On finish it changes back to the original image
public void delayRepeat(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
for (int i = 0; i < whichButton.size(); i++) {
if (whichButton.get(i) == 1) {
buttonRed.setBackgroundResource(endID);
} else if (whichButton.get(i) == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (whichButton.get(i) == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (whichButton.get(i) == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (whichButton.get(i) == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (whichButton.get(i) == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (whichButton.get(i) == 7) {
buttonPink.setBackgroundResource(endID);
} else if (whichButton.get(i) == 8) {
buttonLime.setBackgroundResource(endID);
} else if (whichButton.get(i) == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
for (int i = 0; i < whichButton.size(); i++) {
// TODO Auto-generated method stub
if (whichButton.get(i) == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 9) {
buttonDarkBlue
.setBackgroundResource(newStartID);
}
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
// creating a blinking color button for each specific random number
// On start this method sets the button to the color and waits 1 second
// On finish it changes back to the original image
public void delay(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(endID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (n == 7) {
buttonPink.setBackgroundResource(endID);
} else if (n == 8) {
buttonLime.setBackgroundResource(endID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (n == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (n == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(newStartID);
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
//Used to generate a different random number each time
public int randomNumber() {
randNumber = new Random();
int n = randNumber.nextInt(9) + 1;
return n;
}
// On click for when they click each button
// Buttons are set to specific tags in the onCreate
// Checks if the tag is equal to what the output of whichButton.get(x) is
// If it isn't they fail
public void onClick(View v) {
// TODO Auto-generated method stub
int tag = (Integer) v.getTag();
for (int x = 0; x < whichButton.size(); x++) {
if (tag == 1 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 2 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 3 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 4 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 5 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 6 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 7 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 8 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 9 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else {
aiTurn = false;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
aiTurn = true;
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You failed, would you like to play again?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
}
}
}
In your onClick(...) handler you're calling whenStarted() each time.
In the whenStarted() method you do this...
whichButton = new ArrayList<Integer>();
...which basically sets whichButton to a new empty ArrayList.
Move that line elsewhere in your code so it only initializes the ArrayList at the start of each game and not at every turn.
The way you are going about this is overcomplicated. Instead of using else-if blocks to pick the button from a random number, put the buttons in a list or array and get a random buttons like this:
private final Button[] buttons = new Button[] {
findViewById(R.id.buttonRed),
findViewById(R.id.buttonYellow),
/* etc, etc */
};
public Button getRandomButton() {
return buttons[new Random().nextInt(buttons.length)];
}
The reason the sequence isn't playing back correctly is because you aren't storing the sequence as an instance variable. The easiest way to store the sequence would be to store a list of integers. The integers would represent the position of the buttons in your array and you would add a new entry every turn.
private final List<Integer> currentSequence = new ArrayList<>();
public void nextTurn() {
// first play the previous buttons
for (int i : currentSequence) {
Button b = buttons[i];
// then play it here
}
// play a new button and add it to the sequence
Button randomButton = getRandomButton();
// play it here
currentSequence.add(Arrays.asList(buttons).indexOf(randomButton)));
}
Then when you're done with the current game just remember to clear the sequence with.
currentSequence.clear();