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();
Related
What should the return value at the bottom be? By setting null I can make my app work. However, I would like to get rid of the warning in Android Studio without suppressing it.
Android Studio is obviously telling me "'null' is returned by the method declared as #NonNull".
Is there a better way to return my fragments?
#NonNull
#Override
public Fragment createFragment(int position) {
String className = mContext.getClass().getSimpleName();
// Check which Activity is using the ViewHolder and return the appropriate Fragments.
switch (className) {
case "VancouverActivity":
if (position == 0) {
return new VancouverMainFragment();
} else if (position == 1) {
return new VancouverAttractionsFragment();
} else if (position == 2) {
return new VancouverCoffeeFragment();
} else if (position == 3) {
return new VancouverRestaurantFragment();
} else {
return new VancouverActivitiesFragment();
}
case "SaskatoonActivity":
if (position == 0) {
return new SaskatoonMainFragment();
} else if (position == 1) {
return new SaskatoonAttractionsFragment();
} else if (position == 2) {
return new SaskatoonCoffeeFragment();
} else if (position == 3) {
return new SaskatoonRestaurantFragment();
} else {
return new SaskatoonActivitiesFragment();
}
case "TorontoActivity":
if (position == 0) {
return new TorontoMainFragment();
} else if (position == 1) {
return new TorontoAttractionsFragment();
} else if (position == 2) {
return new TorontoCoffeeFragment();
} else if (position == 3) {
return new TorontoRestaurantFragment();
} else {
return new TorontoActivitiesFragment();
}
case "StJohnsActivity":
if (position == 0) {
return new StJohnsMainFragment();
} else if (position == 1) {
return new StJohnsAttractionsFragment();
} else if (position == 2) {
return new StJohnsCoffeeFragment();
} else if (position == 3) {
return new StJohnsRestaurantFragment();
} else {
return new StJohnsActivitiesFragment();
}
}
return null;
}
The code below is based on a huge quiz I have made. (I have created this code, so it is shorter and thus clearer)
At the beginning an array list contains the Strings a, b, c and d and as the user presses a Button (yes/no) to a certain question, the question is supposed to switch and some of the strings are removed of the array list until there is only one possible string left.
My problem is that as I run the app, the question does not change, although I press Yes/no.
Here is the code:
public class MainActivity extends AppCompatActivity {
static ArrayList<String> p = new ArrayList<String>();
static Button endbutton;
static Button questionbutton;
static Button yesbutton;
static Button nobutton;
static boolean yesbuttonisclicked=false;
static boolean nobuttonisclicked=false;
static boolean beginning=true;
static int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endbutton = findViewById(R.id.endbutton);
questionbutton = findViewById(R.id.questionbutton);
yesbutton = findViewById(R.id.yesbutton);
nobutton = findViewById(R.id.nobutton);
if (beginning)
{
p.add("a");
p.add("b");
p.add("c");
p.add("d");
beginning = false;
}
yesbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesbuttonisclicked=true;
nobuttonisclicked=false;
endbutton.setText("yes");
}
});
nobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nobuttonisclicked=true;
yesbuttonisclicked=false;
endbutton.setText("no");
}
});
List array1 = Arrays.asList("1", "2", "3", "4");
Collections.shuffle(array1);
if (array1.get(i) == "1") {
questionbutton.setText("Question1");
if (yesbuttonisclicked) {
p.remove("a");
p.remove("b");
yesbuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else if(nobuttonisclicked) {
p.remove("c");
p.remove("d");
nobuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
} else if (array1.get(i).equals("2")) {
questionbutton.setText("Question2");
if (yesbuttonisclicked) {
p.remove("a");
p.remove("c");
yesbuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else if(nobuttonisclicked){
p.remove("b");
p.remove("d");
nobuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
} else if (array1.get(i).equals("3")) {
questionbutton.setText("Question3");
if (yesbuttonisclicked) {
p.remove("a");
p.remove("d");
yesbuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else if(nobuttonisclicked){
p.remove("c");
p.remove("b");
nobuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
} else if (array1.get(i).equals("4")) {
questionbutton.setText("Question4");
if (yesbuttonisclicked) {
p.remove("d");
p.remove("c");
yesbuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else if(nobuttonisclicked){
p.remove("a");
p.remove("b");
nobuttonisclicked=false;
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
}
i++;
}
}
The problem should not be in pressing a button, as I have created an additional comment button in which I output yes if the yes button has been pressed and no if no button. So, this should not be the problem.
I just found out, that the program does not switch the booleans yesbuttonisclicked and nobuttonisclicked for some reason. That might be the mistake but I do not know how to fix it...
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
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...
}
How I would like the questions to be like;
When first question is shown, users don't enter the answer. Instead, user has to memorize the answer and with no delay, 2nd question is shown together with the first question still being shown. After every 2 questions, user can only enter the answer for both questions at the same time. However, I'm not sure how to show it in terms of codes. Also, is it possible to go the next question without having to click on the enter button? if it's possible, how do I that?
I want this to happen for the next subsequent questions. I'm still a beginner thus I need some help. I hope I am clear if not, do let me know.
These are my codes;
#Override
public void onClick(View view) {
if (view.getId() == R.id.enter) {
String answerContent = answerTxt.getText().toString();
if(firstQuestion == true)
{
buttonCounter = 1;
firstQuestion = false;
replayBtn.setEnabled(true);
chooseQuestion();
} else if (!answerContent.endsWith("?")) {
int enteredAnswer = Integer.parseInt(answerContent.substring(2));
int exScore = getScore();
if (enteredAnswer == answer){
buttonCounter = 1;
replayBtn.setEnabled(true);
scoreTxt.setText("Score: " + (exScore + 1));
response.setImageResource(R.drawable.tick);
response.setVisibility(View.VISIBLE);
} else {
setHighScore();
buttonCounter = 1;
replayBtn.setEnabled(true);
if (exScore == 0) {
scoreTxt.setText("Score:0");
} else {
scoreTxt.setText("Score: " + (exScore - 1));
}
response.setImageResource(R.drawable.cross);
response.setVisibility(View.VISIBLE);
}
chooseQuestion();
}
} else if (view.getId() == R.id.imageButton1) {
if (buttonCounter == 1) {
replayBtn.setEnabled(false);
Log.d("ins", "called");
}
buttonCounter = 0;
final int DELAY_MS = 1000;
MediaPlayer firstNum = MediaPlayer.create(this,
numberAudioList[operand1]);
firstNum.start();
pauseTimer = true;
firstNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer firstNum) {
firstNum.stop();
firstNum.reset();
firstNum.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer operatorAudio = MediaPlayer.create(this,
operatorAudioList[operator]);
operatorAudio.start();
pauseTimer = true;
operatorAudio.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer operatorAudio) {
operatorAudio.stop();
operatorAudio.reset();
operatorAudio.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer secondNum = MediaPlayer.create(this,
numberAudioList[operand2]);
secondNum.start();
pauseTimer = true;
secondNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer secondNum) {
secondNum.stop();
secondNum.reset();
secondNum.release();
pauseTimer = false;
}
});
if (leftTimeInMillisecondsGlobal == 0) {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(originalTimerTimeInMilliSeconds);
} else {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(leftTimeInMillisecondsGlobal);
}
startTimer();
} else if (view.getId() == R.id.clear) {
cancel = MediaPlayer.create(this, R.raw.cancel);
cancel.start();
cancel.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer cancel) {
cancel.stop();
cancel.reset();
cancel.release();
}
});
answerTxt.setText("= ?");
} else {
response.setVisibility(View.INVISIBLE);
int enteredNum = Integer.parseInt(view.getTag().toString());
if (answerTxt.getText().toString().endsWith("?"))
answerTxt.setText("= " + enteredNum);
else
answerTxt.append("" + enteredNum);
MediaPlayer num = MediaPlayer.create(this,
numberAudioList[enteredNum]);
num.start();
num.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer num) {
num.stop();
num.reset();
num.release();
}
});
}
}
private void setTimer(long timeLeft) {
totalTimeCountInMilliseconds = timeLeft;
timeBlinkInMilliseconds = 20 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (pauseTimer == true) {
leftTimeInMillisecondsGlobal = leftTimeInMilliseconds;
countDownTimer.cancel();
} else {
leftTimeInMillisecondsGlobal = leftTimeInMilliseconds;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
textViewShowTime.setTextAppearance(
getApplicationContext(), R.style.blinkText);
if (blink) {
textViewShowTime.setVisibility(View.VISIBLE);
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
textViewShowTime.setText(String
.format("%02d", seconds / 60)
+ ":"
+ String.format("%02d", seconds % 60));
}
}
#Override
public void onFinish() {
Log.i("check", "check if enter onFinish() method");
setResults();
saveScore();
Log.i("check", "check if passes through");
}
}.start();
}
private int getScore() {
String scoreStr = scoreTxt.getText().toString();
return Integer
.parseInt(scoreStr.substring(scoreStr.lastIndexOf(" ") + 1));
}
private void chooseQuestion() {
answerTxt.setText("= ?"); //first reset the answer Text View
operator = random.nextInt(operators.length);
operand1 = random.nextInt(numberList.length);
operand2 = random.nextInt(numberList.length);
if (operator == 0) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while ((answer > 20));
answer = operand1 + operand2;
} else if (operator == 1) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while ((operand2 > operand1) || answer > 20);
answer = operand1 - operand2;
} else if (operator == 2) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while (operand1 > 12 || operand2 > 12 || (answer > 20));
answer = operand1 * operand2;
} else if (operator == 3) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while (((((double) operand1 / (double) operand2) % 1 > 0)
|| answer > 20 || (operand1 == operand2) || (operand1 == 0) || (operand2 == 0)));
answer = operand1 / operand2;
}
final int DELAY_MS = 1000;
// moved to onClick()
MediaPlayer firstNum = MediaPlayer.create(this,
numberAudioList[operand1]);
pauseTimer = true;
firstNum.start();
firstNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer firstNum) {
firstNum.stop();
firstNum.reset();
firstNum.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer operatorAudio = MediaPlayer.create(this,
operatorAudioList[operator]);
pauseTimer = true;
operatorAudio.start();
operatorAudio.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer operatorAudio) {
operatorAudio.stop();
operatorAudio.reset();
operatorAudio.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer secondNum = MediaPlayer.create(this,
numberAudioList[operand2]);
pauseTimer = true;
secondNum.start();
secondNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer secondNum) {
secondNum.stop();
secondNum.reset();
secondNum.release();
pauseTimer = false;
}
});
int i = getScore();
if (i < 5) {
for (i = 0; i < 5; i++) {
question.setText(operand1 + " " + operators[operator] + " "
+ operand2); //display the question to the user
}
} else {
question.setText("Qns" + (i + 1));
}
// Moved to onClick()
if (leftTimeInMillisecondsGlobal == 0) {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(originalTimerTimeInMilliSeconds);
} else {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(leftTimeInMillisecondsGlobal);
}
startTimer();
}
private int getOperand1() {
operand1 = 0;
do {
operand1 = random.nextInt(numberList.length);
} while (operand1 < 1 || operand1 > 20);
return operand1;
}
private int getOperand2() {
operand2 = 0;
do {
operand2 = random.nextInt(numberList.length);
} while (operand2 < 1 || operand2 > 20);
return operand2;
}
private int getAnswer() {
if (operator == 0) {
answer = operand1 + operand2;
}
else if (operator == 1) {
answer = operand1 - operand2;
}
else if (operator == 2) {
answer = operand1 * operand2;
}
else if (operator == 3) {
answer = operand1 / operand2;
}
return answer;
}
Is it possible to show the second question after first question ? yes it can be done. Use the handler. When you click the button send a message and show the first question. After that show a handler message with delayed time to show the second question.
mHandler.sendEmptyMessage(FIRST_QUESTION_ID);//Fist question willbe shown immediately
mHandler.sendEmptyMessageDelayed(SECOND_QUESTION_ID, 2000)// second question will be shown after 1st question after 2s