I have a game that spawns 4 enemies on screen from image boxes, when a timer reaches zero, an enemy spawns onto the screen. I want a way to constantly check if the enemies are visible or not on screen.
My class currently containing a while loop to check visibility:
public class rear_gunner extends AppCompatActivity {
int clickcount=0;
CountDownTimer countDownTimer;
int score = 0;
int health2 = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rear_gunner);
final TextView text = (TextView) findViewById(R.id.textView2);
final TextView scoreText = (TextView) findViewById(R.id.score);
final TextView health = (TextView) findViewById(R.id.Health);
health.setText("Health:"+ health2);
//Enemy ImageViews
final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
final ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
final ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
final ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);
//sets screen orientation on created
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//sets imageViews into array
final ImageView[] enemies = new ImageView[4];
enemies[0] = enemy1;
enemies[1] = enemy2;
enemies[2] = enemy3;
enemies[3] = enemy4;
boolean running = true;
while (!running) {
if (enemy1.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy2.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy3.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy4.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
}
The above code just simply does not work. When I start the activity the screen goes black and remains like that until closed. Does this have anything to do with the way I am using the while loop for running?
My timer code if needed:
//random number generator between 10-25
Random r = new Random();
int Low = 10000;
int High = 25000;
int Result = r.nextInt(High-Low) + Low;
//count down timer for spawing enemies
countDownTimer = new CountDownTimer(Result, 1000) {
#Override
public void onTick(long millisUntilFinished) {
text.setText("seconds remaining: " + millisUntilFinished / 1000);
if (score == 500)
{
countDownTimer.cancel();
}
}
#Override
public void onFinish() {
Random r = new Random();
int Low = 0;
int High = 4;
int Result = r.nextInt(High-Low) + Low;
enemies[Result].setVisibility(View.VISIBLE);
countDownTimer.start();
if (score == 500)
{
countDownTimer.cancel();
}
}
};
countDownTimer.start();
}
}
Thank you for all the help and any advice for a more efficient way of doing this would be greatly appriciated.
boolean running = true;
while (!running) {
...
Your while loop never get chance to run, if you want refresh UI, you must write this code in another place, maybe a background Timer task thread or use Handler to deal with this.
Related
I have a piece of code that compares to images and places a marker on the difference. So far it works well, except the latest marker layer that is added always shows underneath all the older markers. I have the latest one as a yellow color and the older ones as red. When the difference is close to one of the red markers, the yellow marker shows behind those ones.
Is there anyone that can help me get the yellow (Latest marker) to appear on top?
This is my code so far:
public class CheckmarkActivity extends AppCompatActivity implements ZoomLayout.OnZoomableLayoutClickEventListener {
TextView tv;
RelativeLayout relativeLayout_work;
ImageView imageViewtest;
Bitmap prevBmp = null;
Timer t;
TimerTask task;
int time = 100;
float image_Width;
float image_Height;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkmark);
if (getResources().getBoolean(R.bool.is_tablet)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
tv = findViewById(R.id.tv);
relativeLayout_work = findViewById(R.id.relativeLayout_work);
imageViewtest = findViewById(R.id.imageViewtest);
prevBmp = ViewcontrollerActivity.workSession.getLastScreenShot();
if (prevBmp == null || ViewcontrollerActivity.workSession.workScreenShot == null) {
setResult(Activity.RESULT_CANCELED);
finish();
}
startTimer();
}
// image compare
class TestAsync extends AsyncTask<Object, Integer, String>
{
String TAG = getClass().getSimpleName();
PointF p;
Bitmap test_3;
protected void onPreExecute (){
super.onPreExecute();
Log.d(TAG + " PreExceute","On pre Exceute......");
}
protected String doInBackground(Object...arg0) {
test_3 = ImageHelper.findDifference(CheckmarkActivity.this, prevBmp, ViewcontrollerActivity.workSession.workScreenShot);
p = ImageHelper.findShot(test_3);
time = 1;
return "You are at PostExecute";
}
protected void onProgressUpdate(Integer...a){
super.onProgressUpdate(a);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
addImageToImageview();
PointF np = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
tv.setX(np.x - tv.getWidth() / 2);
tv.setY(np.y - tv.getHeight() / 2);
tv.setVisibility(View.VISIBLE);
// imageViewtest.setImageBitmap(test_3);
}
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i("OpenCV", "OpenCV loaded successfully");
new TestAsync().execute();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
#Override
protected void onResume() {
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d("OpenCV", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d("OpenCV", "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public static int[] getBitmapOffset(ImageView img, Boolean includeLayout) {
int[] offset = new int[2];
float[] values = new float[9];
Matrix m = img.getImageMatrix();
m.getValues(values);
offset[0] = (int) values[5];
offset[1] = (int) values[2];
if (includeLayout) {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) img.getLayoutParams();
int paddingTop = (int) (img.getPaddingTop() );
int paddingLeft = (int) (img.getPaddingLeft() );
offset[0] += paddingTop + lp.topMargin;
offset[1] += paddingLeft + lp.leftMargin;
}
return offset;
}
public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
int[] ret = new int[4];
if (imageView == null || imageView.getDrawable() == null)
return ret;
// Get image dimensions
// Get image matrix values and place them in an array
float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = imageView.getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
ret[2] = actW;
ret[3] = actH;
// Get image position
// We assume that the image is centered into ImageView
int imgViewW = imageView.getWidth();
int imgViewH = imageView.getHeight();
int top = (int) (imgViewH - actH)/2;
int left = (int) (imgViewW - actW)/2;
ret[0] = left;
ret[1] = top;
return ret;
}
private void addImageToImageview(){
if (ViewcontrollerActivity.workSession.workScreenShot != null) {
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
Log.d("width", String.valueOf(imageViewtest.getWidth()));
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
for (int i = 0; i < ViewcontrollerActivity.workSession.getShotCount(); i++) {
PointF p = ViewcontrollerActivity.workSession.getPoint(i);
TextView t = new TextView(this);
t.setText("" + (i + 1));
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams((int)px, (int)px);
relativeLayout_work.addView(t);
t.setLayoutParams(param);
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.circle);
p = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
t.setX(p.x);
t.setY(p.y);
t.setTag(10000 + i);
}
}
public void onConfirm(View v){
View vv = findViewById(R.id.relativeLayout_work);
PointF bp = Session.convertPointView2Bitmap(new PointF(tv.getX(), tv.getY()), relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
ViewcontrollerActivity.workSession.addNewShot(ViewcontrollerActivity.workSession.workScreenShot, bp);
setResult(Activity.RESULT_OK);
finish();
}
public void onCancel(View v){
setResult(Activity.RESULT_CANCELED);
finish();
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
finish();
}
#Override
public void OnContentClickEvent(int action, float xR, float yR) {
int[] offset = new int[2];
int[] rect = new int[4];
offset = this.getBitmapOffset(imageViewtest, false);
int original_width = imageViewtest.getDrawable().getIntrinsicWidth();
int original_height = imageViewtest.getDrawable().getIntrinsicHeight();
rect = getBitmapPositionInsideImageView(imageViewtest);
Log.i("OffsetY", String.valueOf(offset[0]));
Log.i("OffsetX", String.valueOf(offset[1]));
Log.i( "0", String.valueOf(rect[0]));
Log.i( "1", String.valueOf(rect[1]));
Log.i( "2", String.valueOf(rect[2]));
Log.i( "3", String.valueOf(rect[3]));
if (xR > rect[0] && xR < rect[0] + rect[2] && yR > rect[1] && yR < rect[1] + rect[3]) {
tv.setX(xR - tv.getWidth() / 2);
tv.setY(yR - tv.getHeight() / 2);
}
// tv.setX(xR - tv.getWidth() / 2);
// tv.setY(yR - tv.getHeight() / 2);
}
public void onMoveButtonPressed(View v) {
ImageButton b = (ImageButton)v;
int mId = b.getId();
switch (mId) {
case R.id.imageButtonL:
tv.setX(tv.getX() - 1);
break;
case R.id.imageButtonR:
tv.setX(tv.getX() + 1);
break;
case R.id.imageButtonD:
tv.setY(tv.getY() + 1);
break;
case R.id.imageButtonU:
tv.setY(tv.getY() - 1);
break;
}
}
//timer change image
public void startTimer(){
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (time == 1){
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
// tv.setVisibility(View.VISIBLE);
tv.setText("" + (ViewcontrollerActivity.workSession.getShotCount() + 1));
t.cancel();
return;
}
if (time % 2 == 0) {
imageViewtest.setImageBitmap(prevBmp);
}
else if(time % 2 == 1){
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
}
time --;
}
});
}
};
t.scheduleAtFixedRate(task, 0, 500);
}
}
You can give the z-order of the child view with addView() function.
void addView (View child, int index)
ex)
private void addImageToImageview(){
if (ViewcontrollerActivity.workSession.workScreenShot != null) {
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
Log.d("width", String.valueOf(imageViewtest.getWidth()));
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
int currChildrenCount = relativeLayout_work.getChildCount();
for (int i = 0; i < ViewcontrollerActivity.workSession.getShotCount(); i++) {
PointF p = ViewcontrollerActivity.workSession.getPoint(i);
TextView t = new TextView(this);
t.setText("" + (i + 1));
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams((int)px, (int)px);
relativeLayout_work.addView(t, currChildrenCount+i); // You can control the order like this
t.setLayoutParams(param);
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.circle);
p = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
t.setX(p.x);
t.setY(p.y);
t.setTag(10000 + i);
}
}
I am practising on a simple Android Game where a round button is randomly placed on the screen when the user taps on it..
it works fine but i want to speedify the process of placing the button so that the game gets harder for user...
here is the Code I'm using -
public class GameWindow extends Activity implements View.OnClickListener {
static int score;
private Timer t;
private int TimeCounter = 29;
private boolean canMove = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
////Remove title screen for activty.
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_game_window);
moveButton();
endonTimeOver();
}
public void endonTimeOver(){
////Activity timer for 60 seconds.
final TextView timer = (TextView) findViewById(R.id.seconds);
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
////Set string to timer.
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
timer.setText(String.valueOf(TimeCounter)); // you can set it to a textView to show it to the user to see the time passing while he is writing.
TimeCounter = TimeCounter - 1;
}
});
}
}, 1000, 1000); // 1000 means start from 1 sec, and the second 1000 is do the loop each 1 sec.
new Timer().schedule(new TimerTask(){
public void run() {
GameWindow.this.runOnUiThread(new Runnable() {
public void run() {
startActivity(new Intent(GameWindow.this, Finished.class));
}
});
}
}, 30000);
}
////Move button.
private void moveButton()
{
if(!canMove){ return; }
runOnUiThread(
new Runnable()
{
#Override
public void run()
{
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Button button = (Button)findViewById(R.id.button);
Random r = new Random();
int startX = width/2;
int startY = height/2;
if(score==0){
button.setX(startX);
button.setY(startY);
}
else {
int x = r.nextInt(width - 210);
int y = r.nextInt(height - 200);
button.setX(x);
button.setY(y);
}
}
}
);
}
////Display score
public void displayScore(int score) {
TextView scoreView = (TextView) findViewById(R.id.score);
scoreView.setText(String.valueOf(score));
}
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonsound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
score = score + 1;
displayScore(score);
switch (v.getId()) {
case (R.id.button): {
moveButton();
}
}
}
public static int getScore(){
return score;
}}
Use global variables for values that don't change:
findViewById is slow
Creating new Random every time is not necessary
getting the window parameter every time is not necessary either
You seem to be starting a new thread and telling it to runonui , this might be slowing you down , try this :
private void moveButton()
{
if(!canMove){ return; }
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Button button = (Button)findViewById(R.id.button);
Random r = new Random();
int startX = width/2;
int startY = height/2;
if(score==0){
button.setX(startX);
button.setY(startY);
}
else {
int x = r.nextInt(width - 210);
int y = r.nextInt(height - 200);
button.setX(x);
button.setY(y);
}
}
the computation itself doesn't seem to heavy so no need for another thread , you can do it on the main thread , if you're calling from oncreate that means you're already on main thread , this might give you the answer if i understood the question , try it
I am trying to make a two player tic-tac-toe game. When the first player clicks the OnClick method with mark X on the button, but I stuck - I don't know how to make the onClick() to detect when the 2nd player clicked and how to mark O on the button ..plz help.. My .java is below
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBoard();
}
int c[][];
int i, j, k = 0;
Button b[][];
TextView textView;
private void setBoard() {
b = new Button[4][4];
c = new int[4][4];
// Button = (TextView) findViewById(R.id.newgame);
b[1][3] = (Button) findViewById(R.id.one);
b[1][2] = (Button) findViewById(R.id.two);
b[1][1] = (Button) findViewById(R.id.three);
b[2][3] = (Button) findViewById(R.id.four);
b[2][2] = (Button) findViewById(R.id.five);
b[2][1] = (Button) findViewById(R.id.six);
b[3][3] = (Button) findViewById(R.id.seven);
b[3][2] = (Button) findViewById(R.id.eight);
b[3][1] = (Button) findViewById(R.id.nine);
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++)
c[i][j] = 2;
}
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
b[i][j].setOnClickListener(new MyClickListener(i, j));
if (!b[i][j].isEnabled()) {
b[i][j].setText("o");
b[i][j].setEnabled(true);
}
}
}
}
class MyClickListener implements View.OnClickListener {
int x;
int y;
public MyClickListener(int x, int y) {
this.x = x;
this.y = y;
}
public void onClick(View view) {
if (b[x][y].isEnabled()) {
b[x][y].setEnabled(false);
b[x][y].setText("X");
c[x][y] = 0;
textView.setText("");
//WHAT NEXT
}
}
}
}
}
Simply use a boolean to detetct the click. Say a boolean isFirstPlayerTurn is true when button is clicked first time. Make it false for second turn. Do this for all turns and you will know which player is clicking the button.
Example:
private boolean isFirstPlayerTurn = true;
...
void onclick() {
if (isFirstPlayerTurn) {
// clicked by player 1
isFirstPlayerTurn = false;
} else {
// clicked by player 2
isFirstPlayerTurn = true;
}
}
You should probably add a new variable
int playerTurn;
which should initially be set to 1. On the first onClick() execution, the value of playerTurn is 1, so place an X, and change the playerTurn to 2. On the second click, when you check the value of playerTurn, you will place an O, and change its value to 1. And this keep on going.
int player = 1;
public void onClick(View view){
if (b[x][y].isEnabled() {
b[x][y].setEnabled(false);
if (player == 1){
b[x][y].setText("X");
c[x][y] = 0;
player = 1;
} else {
b[x][y].setText("O");
c[x][y] = 1;
player = 2;
}
}
}
I'm trying to implement a CountDownTimer in an Android Application. This timer will, while running, countdown from a value, than reset, than countdown from a different value. Switching back and force between values until either a set number of rounds have elapsed or the stop button has been pressed. I can get the CountDownTimer samples to work, but I guess I'm missing something here. Below is the applicable button press code;
CounterState state = CounterState.WORKOUT;
private WorkoutTimer workoutTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_stopwatch);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set up OnClickListeners
((Button) findViewById(R.id.start_button)).setOnClickListener(this);
((Button) findViewById(R.id.stop_button)).setOnClickListener(this);
((Button) findViewById(R.id.reset_button)).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.start_button:
if (!timer_running) {
timer_running = true;
Log.d(TAG, "clicked on Start Button");
// If the state is unknown, set it to Workout first
int State = state.getStateValue();
if (State == 0) {
state.setStateValue(1);
}
workoutTimer.start();
}
break;
case R.id.stop_button:
Log.d(TAG, "clicked on Stop Button");
if (timer_running); {
timer_running = false;
workoutTimer.cancel();
}
break;
private class WorkoutTimer extends CountDownTimer{
public WorkoutTimer(long interval) {
super(getThisTime(), interval);
Log.d(TAG, "WorkoutTimer Constructed...");
}
TextView digital_display = (TextView) findViewById(R.id.digital_display);
TextView numOfRounds = (TextView) findViewById(R.id.number_of_rounds);
public void onFinish() {
int State = state.getStateValue();
int roundsLeft = 0;
if (State == 1) {
state.setStateValue(2);
} else {
state.setStateValue(1);
}
decrementRounds();
try {
roundsLeft = Integer.parseInt(numOfRounds.getText().toString());
} catch(NumberFormatException nfe) {
roundsLeft = 999;
}
if (roundsLeft > 0 || roundsLeft != 999) {
workoutTimer.start();
}
}
public void onTick(long millisUntilFinished) {
final long minutes_left = ((millisUntilFinished / 1000) / 60);
final long seconds_left = (millisUntilFinished / 1000) - (minutes_left * 60);
final long millis_left = millisUntilFinished % 100;
String time_left = String.format("%02d:%02d.d", minutes_left, seconds_left,
millis_left);
digital_display.setText(time_left);
}
}
private long getThisTime() {
long time = 0;
TextView workout_time = (TextView) findViewById(R.id.workout_time);
TextView rest_time = (TextView) findViewById(R.id.rest_time);
switch(state) {
case WORKOUT:
try {
time = Integer.parseInt(workout_time.getText().toString());
} catch(NumberFormatException nfe) {
time = 999;
}
// time = 90;
Log.d(TAG, "Workout time = " + time);
break;
case REST:
try {
time = Integer.parseInt(rest_time.getText().toString());
} catch(NumberFormatException nfe) {
time = 999;
}
// time = 30;
Log.d(TAG, "Rest time = " + time);
break;
case UNKNOWN:
time = 0;
break;
}
return time;
}
Everything starts up okay, but crashes when I click either button. If I comment out my calls to the workoutTimer, no crash. I never see my log in the constructor of the workoutTimer class, so obviously I'm missing something here. Any help would be appreciated.
-Ian
You have not initialized your workoutTimer. You need to add the following line in your onCreate method.
workoutTimer = new WorkoutTimer(...);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Ok so here is my problem. I am working on a trivia game that uses a question counter to display 10 questions and once that happens it calls the finalscore class. I have implemented a timer that resets for every question and if time runs up it proceeds to the next question. However if nothing is clicked on the final question it will keep looping back to the finalscore class even after starting a new game.
public class game extends Activity implements OnClickListener {
// int[] anArray;
int[] anArray2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int numberOfQuestionsDisplayedCounter = 0;
int nextOrFinishValue = 0;
int randomValueZeroToThree = 0;
int randomValue0to29 = 0;
boolean alreadyDisplayQuestion = false;
boolean validQuestionNumber = false;
boolean rightButton1 = false;
boolean rightButton2 = false;
boolean rightButton3 = false;
boolean rightButton4 = false;
String questionFromDatabase;
String answer1FromDatabase;
String answer2FromDatabase;
String answer3FromDatabase;
String answer4FromDatabase;
String displayedQuestionFromDatabase = "question ";
String displayedAnswer1FromDatabase = "answer1a ";
String displayedAnswer2FromDatabase = "answer2a ";
String displayedAnswer3FromDatabase = "answer3a ";
String displayedAnswer4FromDatabase = "answer4a ";
int categoryId = 0;
int questionId = 0;
int currentScore = 0;
private CountDownTimer mCountDown;
public void onCreate(Bundle savedInstanceState) {
int randomInt = 1;
super.onCreate(savedInstanceState);
categoryId = com.triviagame.Trivia_Game.categoryIdInMainMenu;
// System.out.println("categoryID =" + categoryId);
setContentView(R.layout.displayquestion);
// gathers question and answers from database
gatherInfoBeforePopulating(); // includes generating random number
// between getting info from database 1
// to 30
// displays question, answers, score
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
// Sets buttons and listers for the buttons with the 4 possible answers
View answer1button = findViewById(R.id.answer1button);
answer1button.setOnClickListener(this);
View answer2button = findViewById(R.id.answer2button);
answer2button.setOnClickListener(this);
View answer3button = findViewById(R.id.answer3button);
answer3button.setOnClickListener(this);
View answer4button = findViewById(R.id.answer4button);
answer4button.setOnClickListener(this);
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
// Displays question, answers, score
public void populateWithQuestionInfo(String question, String answer1,
String answer2, String answer3, String answer4,
int nextQuestionOrFinish) {
// populate the question label
TextView questionLabel = (TextView) findViewById(R.id.question);
questionLabel.setText(question);
// populate answer1
Button buttonAnswer1 = (Button) findViewById(R.id.answer1button);
buttonAnswer1.setText(answer1);
// populate answer2
Button buttonAnswer2 = (Button) findViewById(R.id.answer2button);
buttonAnswer2.setText(answer2);
// populate answer3
Button buttonAnswer3 = (Button) findViewById(R.id.answer3button);
buttonAnswer3.setText(answer3);
// populate answer4
Button buttonAnswer4 = (Button) findViewById(R.id.answer4button);
buttonAnswer4.setText(answer4);
numberOfQuestionsDisplayedCounter++;
}
// Generates a random number between 0 and 3 to be used to display the
// possible answers randomly
int RandomGeneratorZeroToThree() {
int randomInt = 0;
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(4);
}
return randomInt;
}
// Generates a random number between 0 and 29 to be used to select the
// question to be displayed
int RandomGenerator0To29() {
int randomInt2 = 0;
Random randomGenerator2 = new Random();
for (int idx2 = 1; idx2 <= 10; ++idx2) {
randomInt2 = randomGenerator2.nextInt(30);
}
return randomInt2;
}
// returns true if the question has already been displayed
// returns false if the question has not been already displayed
boolean questionsAlreadyDisplayed(int randomValue0to29) {
for (int i = 0; i < 10; i++) {
if (anArray2[i] == randomValue0to29) {
return true; // question already displayed
}
}
anArray2[numberOfQuestionsDisplayedCounter] = randomValue0to29; // questionId
// added
// to
// array
// of
// displayed
// questions
return false; // random number can be used as it has been used already
}
// Connects to the database to gather the question and 4 possible answers.
// Uses DataBaseHelper class
void getInfoFromDatabase(int categoryId, int questionId) {
DataBaseHelper myDbHelper = new DataBaseHelper(
this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
questionFromDatabase = myDbHelper.getQuestion(categoryId,
questionId);
displayedQuestionFromDatabase = questionFromDatabase;
System.out
.println("questionFromDatabase = " + questionFromDatabase);
answer1FromDatabase = myDbHelper.getCorrectAnswer(categoryId,
questionId); // correct answer from database
System.out.println("correct answer from db = "
+ answer1FromDatabase);
answer2FromDatabase = myDbHelper.getWrongAnswer1(categoryId,
questionId);
answer3FromDatabase = myDbHelper.getWrongAnswer2(categoryId,
questionId);
answer4FromDatabase = myDbHelper.getWrongAnswer3(categoryId,
questionId);
myDbHelper.close();
} catch (SQLException sqle) {
System.out.println("Errored out");
try {
throw sqle;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// If the player selects the right answer this method is called to increase
// the score by 10 points
void increaseScore() {
currentScore = currentScore + 10;
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// If the player selects the wrong answer this method is called to decrease
// the score by 10 points
void decreaseScore() {
currentScore = currentScore - 10;
// score can't go below 0
if (currentScore < 0) {
currentScore = 0;
}
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// Displays the current scores on the activity
void displayScore() {
TextView yourScore = (TextView) findViewById(R.id.yourscore);
String currentScoreText;
currentScoreText = Integer.toString(currentScore);
yourScore.setText(currentScoreText);
}
void resetTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
void questionCheck() {
if (nextOrFinishValue == 1) {
Intent e = new Intent(this, finalscore.class);
startActivity(e);
cancelTimer();
}
if (nextOrFinishValue == 0) { // If 10 questions have not been displayed
// yet, display the next question
gatherInfoBeforePopulating();
displayScore();
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
}
}
// gathers question and answers from database
void gatherInfoBeforePopulating() {
categoryId = Trivia_Game.getCategoryIdInMainMenu();
// Loop until a valid questionId that hasn't been used is obtained
while (validQuestionNumber == false) {
randomValue0to29 = RandomGenerator0To29();
System.out.println("random30 in onClick = " + randomValue0to29);
alreadyDisplayQuestion = questionsAlreadyDisplayed(randomValue0to29);
if (alreadyDisplayQuestion == true) {
System.out
.println("question number already displayed looking for a non displayed question");
}
if (alreadyDisplayQuestion == false) {
System.out.println("question not displayed yet");
validQuestionNumber = true;
}
}
validQuestionNumber = false;
alreadyDisplayQuestion = false;
questionId = randomValue0to29; // sets the valid random generated number
// to the questionID
// connect to database to gather the question and answers
getInfoFromDatabase(categoryId, questionId);
// Calls random number from 0 to 3 to determine which button will
// display the correct answer
randomValueZeroToThree = RandomGeneratorZeroToThree();
System.out.println("random4 in onClick = " + randomValueZeroToThree);
// Sets the order according to the button that is to display the correct
// answer
switch (randomValueZeroToThree) {
case 0:
displayedAnswer1FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = true;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
break;
case 1:
displayedAnswer2FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = true;
rightButton3 = false;
rightButton4 = false;
break;
case 2:
displayedAnswer3FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer2FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = true;
rightButton4 = false;
break;
case 3:
displayedAnswer4FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer2FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = true;
break;
default:
displayedAnswer1FromDatabase = answer4FromDatabase; // no correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer1FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
}
// After the 9th question is displayed, the nextOfFinishValue should be
// set to 1 so the button displayes Finish instead of Next
if (numberOfQuestionsDisplayedCounter < 9) {
nextOrFinishValue = 0;
} else {
nextOrFinishValue = 1;
}
}
// Listeners for the 4 buttons with answers and the Next or Finish buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.answer1button:
if (rightButton1 == true) {
increaseScore();
resetTimer();
// put here to change color of button
} else {
decreaseScore();
resetTimer();
// change button to red
}
questionCheck();
break;
case R.id.answer2button:
if (rightButton2 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer3button:
if (rightButton3 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer4button:
if (rightButton4 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
}
}
#Override
protected void onResume() {
super.onResume();
music.play(this, R.raw.musicbackground); // play background music
}
#Override
protected void onPause() {
super.onPause();
music.stop(this); // stop playing background music
}
}
mCountdown is never null so change your code
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
To
void cancelTimer() {
mCountDown.cancel();
}