Clicking a button 3 times in a row to trigger a toast? - java

I was just wondering how to create a toast (or trigger something else to happen) when clicking on button 3 times in a row?
For example: I've created a coin flip so far and I want a toast to appear if the user manages to get 3 heads/tails in a row.
This is my current code:
if (randomNumber == 1) {
Log.i("Result", "Heads");
greycoin.animate().alpha(0).setDuration(1000).rotationYBy(1800);
redcoin.animate().alpha(1).setDuration(1000).rotationYBy(1800);
view.animate()
.withEndAction(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Heads", Toast.LENGTH_SHORT).show();
}
})
.start();
} else {
Log.i("Result", "Tails");
greycoin.animate().alpha(1).setDuration(1000).rotationYBy(1800);
redcoin.animate().alpha(0).setDuration(1000).rotationYBy(1800);
view.animate()
.withEndAction(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Tails", Toast.LENGTH_SHORT).show();
}
})
.start();
}
}
I'm still incredibly new to Java and programming, so please pardon my poor programming vocabulary.
Thank you very much in advance!

you should use the gesture instead:
view.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 3) {
Toast.makeText(getApplicationContext(), "triple click", Toast.LENGTH_SHORT).show();
//handle triple tap
}
return true;
}
});

Related

Why the animation does not change the text of the button to the next click?

When I press the first time the buttons go and come back with other
letters, but when I press again nothing happens:
int d = -1; String btnanim = "0";
How to make it animated when I press the buttons again?
public void b_b1(View v) {
if (this.btnanim == "AB") {
btn("CD");
return;
}
do {
if (this.btnanim == "CD") {
btn("EF");
return;
}
if (this.btnanim == "EF") {
btn("GH");
return;
}
} while (this.btnanim != "1");
btn("AB");
}
Without animation, the text changes
void btn(String str) {
this.btnanim = str;
this.timer.schedule(new TimerTask() {
ObjectAnimator anim;
LinearLayout bgroup = (LinearLayout) MainActivity.this.findViewById(R.id.bg);
Button b1 = (Button) MainActivity.this.findViewById(R.id.b1);
Button b2 = (Button) MainActivity.this.findViewById(R.id.b2);
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
MainActivity.this.d += 1;
switch (MainActivity.this.d) {
case 0:
anim = ObjectAnimator.ofFloat(bgroup, "translationX", bgroup.getWidth() * 2);
anim.setDuration(500L).start();
break;
case 5:
anim = ObjectAnimator.ofFloat(bgroup, "translationX", -bgroup.getWidth() * 2);
anim.setDuration(0L).start();
anim = ObjectAnimator.ofFloat(bgroup, "translationX", 0);
anim.setDuration(500L).start();
switch (MainActivity.this.btnanim) {
case "AB":
b1.setText("A");
b2.setText("B");
break;
case "CD":
b1.setText("C");
b2.setText("D");
break;
case "EF":
//Do not repeat the animation this: Changes A and B to C and D then nothing
b1.setText("E");
b2.setText("F");
break;
}
}
}
});
}
}, 0L, 100L);
}
protected void onResume() {
super.onResume();
MainActivity.this.btnanim = "AB";
}
}
I added this.d = -1; in void btn(String str) {}
Now it works right!

How to create game loop for Android Wear app

What I'm trying to do is make an version of the game Simon for android wear. I don't want to use libgdx, tho I could if I have no other choice.
The way the game works is that the computer shows a button sequence to the player and then the player is to repeat the sequence back. I've got it all working fine except for I can't seem to animate a sequence to the player.
What I have is a random number generator. Using the number generated I want to change the color of the button background for a small time, then change it back. And I loop this a set number of times. I've tried SystemClock.sleep(500), but it just runs the loop before even showing the app.
The main problem is that everything has to be done inside an onLayoutInflated because of how wear has to choose between round and square faces. And this has to be done in the onCreate method as far as I know.
Does anyone know a way of doing some sort of game loop and/or animation sequence for android wear.
P.S. I will append my code as soon as I fix it. I've been fiddling with it a lot.
package com.happypantzinc.memory;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.wearable.view.WatchViewStub;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends Activity {
private ImageButton mOverlay, mTopLeft, mTopRight, mBotLeft, mBotRight;
private Boolean isPlayerTurn = false;
private Boolean isRunning = false;
private Random random = new Random();
private int level = 10;
private ArrayList<Integer> compSeq;
private ArrayList<Integer> playSeq;
private float screenW, screenH;
//setup colors
final int RED_UP = Color.rgb(180, 0, 0);
final int RED_DOWN = Color.rgb(255, 77, 0);
final int GREEN_UP = Color.rgb(0, 180, 0);
final int GREEN_DOWN = Color.rgb(0, 255, 77);
final int BLUE_UP = Color.rgb(0, 0, 180);
final int BLUE_DOWN = Color.rgb(0, 77, 255);
final int YELLOW_UP = Color.rgb(180, 180, 0);
final int YELLOW_DOWN = Color.rgb(255, 255, 0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
compSeq = new ArrayList<Integer>();
playSeq = new ArrayList<Integer>();
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mOverlay = (ImageButton) stub.findViewById(R.id.overlay);
mTopLeft = (ImageButton) stub.findViewById(R.id.topLeft);
mTopRight = (ImageButton) stub.findViewById(R.id.topRight);
mBotLeft = (ImageButton) stub.findViewById(R.id.botLeft);
mBotRight = (ImageButton) stub.findViewById(R.id.botRight);
setupButtons();
setupButtonActions(mTopLeft, GREEN_UP, GREEN_DOWN);
setupButtonActions(mTopRight, RED_UP, RED_DOWN);
setupButtonActions(mBotLeft, YELLOW_UP, YELLOW_DOWN);
setupButtonActions(mBotRight, BLUE_UP, BLUE_DOWN);
mOverlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isRunning = true;
mOverlay.setClickable(false);
mOverlay.setVisibility(View.GONE);
gameLoop();
}
});
}
});
//get screen size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenW = size.x;
screenH = size.y;
}
private void gameLoop() {
while(isRunning) {
//Computer turn
while (compSeq.size() < level) {
int val = random.nextInt(4);
if (!mOverlay.isShown()) {
//Computer shows sequence
switch (val) {
case 0:
mTopLeft.getBackground().setColorFilter(GREEN_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mTopLeft.getBackground().setColorFilter(GREEN_UP, PorterDuff.Mode.MULTIPLY);
break;
case 1:
mTopRight.getBackground().setColorFilter(RED_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mTopRight.getBackground().setColorFilter(RED_UP, PorterDuff.Mode.MULTIPLY);
break;
case 2:
mBotLeft.getBackground().setColorFilter(YELLOW_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mBotLeft.getBackground().setColorFilter(YELLOW_UP, PorterDuff.Mode.MULTIPLY);
break;
case 3:
mBotRight.getBackground().setColorFilter(BLUE_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mBotRight.getBackground().setColorFilter(BLUE_UP, PorterDuff.Mode.MULTIPLY);
break;
default:
break;
}
compSeq.add(val);
SystemClock.sleep(300);
}
}
isPlayerTurn = true;
while (playSeq.size() < level) {
//Check for correct input
if (playSeq.size() > 0 && (playSeq.get(playSeq.size()-1) != compSeq.get(playSeq.size()-1))) {
isRunning = false;
break;
}
}
playSeq.clear();
compSeq.clear();
isPlayerTurn = false;
}
}
private void setupButtons() {
//set width and height of buttons
android.view.ViewGroup.LayoutParams params;
params = mOverlay.getLayoutParams();
params.height = (int) screenH;
params.width = (int) screenW;
mOverlay.setLayoutParams(params);
params = mTopLeft.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mTopLeft.setLayoutParams(params);
params = mTopRight.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mTopRight.setLayoutParams(params);
params = mBotLeft.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mBotLeft.setLayoutParams(params);
params = mBotRight.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mBotRight.setLayoutParams(params);
//set position of buttons
mOverlay.setX(0);
mOverlay.setY(0);
mTopLeft.setX(0);
mTopLeft.setY(0);
mTopRight.setX(screenW / 2);
mTopRight.setY(0);
mBotLeft.setX(0);
mBotLeft.setY(screenH / 2);
mBotRight.setX(screenW / 2);
mBotRight.setY(screenH / 2);
//set initial background tints
mTopLeft.getBackground().setColorFilter(GREEN_UP, PorterDuff.Mode.MULTIPLY);
mTopRight.getBackground().setColorFilter(RED_UP, PorterDuff.Mode.MULTIPLY);
mBotLeft.getBackground().setColorFilter(YELLOW_UP, PorterDuff.Mode.MULTIPLY);
mBotRight.getBackground().setColorFilter(BLUE_UP, PorterDuff.Mode.MULTIPLY);
}
private void setupButtonActions(final ImageButton button, final int tint_up, final int tint_down) {
//create button listeners and tints
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isPlayerTurn) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
button.getBackground().setColorFilter(tint_down, PorterDuff.Mode.MULTIPLY);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
button.getBackground().setColorFilter(tint_up, PorterDuff.Mode.MULTIPLY);
}
//Enter correct sequence value
int val = 4;
if (button == mTopLeft) {
val = 0;
} else if (button == mTopRight) {
val = 1;
} else if (button == mBotLeft) {
val = 2;
} else if (button == mBotRight) {
val = 3;
}
playSeq.add(val);
}
return false;
}
});
}
}
You should not use SystemClock.sleep() as you are blocking the UI thread. Probably this is the cause that the animation is done before showing the activity (The activity will not show until onCreate() finishes). This can also cause the famous ANR dialog.
You can use Handlers to do the work later without blocking the UI thread:
private Handler mHandler;
private int
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
computerTurnDown();
}
}, 500); //Delay time in ms
...
}
private void computerTurnDown(){
final int val = random.nextInt(4);
if (!mOverlay.isShown()) {
//Computer shows sequence
switch (val) {
case 0:
mTopLeft.getBackground().setColorFilter(GREEN_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
case 1:
mTopRight.getBackground().setColorFilter(RED_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
case 2:
mBotLeft.getBackground().setColorFilter(YELLOW_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
case 3:
mBotRight.getBackground().setColorFilter(BLUE_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
default:
break;
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
computerTurnUp(val);
}
}, 500);
}
private void computerTurnUp(){
switch (val) {
case 0:
mTopLeft.getBackground().setColorFilter(GREEN_UP, PorterDuff.Mode.MULTIPLY);
break;
case 1:
mTopRight.getBackground().setColorFilter(RED_UP, PorterDuff.Mode.MULTIPLY);
break;
case 2:
mBotLeft.getBackground().setColorFilter(YELLOW_UP, PorterDuff.Mode.MULTIPLY);
break;
case 3:
mBotRight.getBackground().setColorFilter(BLUE_UP, PorterDuff.Mode.MULTIPLY);
break;
default:
break;
}
compSeq.add(val);
if (compSeq.size() < level){
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
computerTurnDown();
}
}, 300);
}else{
isPlayerTurn = true;
}
}
Whenever you want to do some work delayed use mHandler.postDelayed() and put the code in run() method.
To check the user should be done in the button listener because the way you have currently the "while (playSeq.size() < level)" will block the thread.
private void setupButtonActions(final ImageButton button, final int tint_up, final int tint_down) {
//create button listeners and tints
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isPlayerTurn) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
button.getBackground().setColorFilter(tint_down, PorterDuff.Mode.MULTIPLY);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
button.getBackground().setColorFilter(tint_up, PorterDuff.Mode.MULTIPLY);
}
//Enter correct sequence value
int val = 4;
if (button == mTopLeft) {
val = 0;
} else if (button == mTopRight) {
val = 1;
} else if (button == mBotLeft) {
val = 2;
} else if (button == mBotRight) {
val = 3;
}
playSeq.add(val);
if(playSeq.size() < level) {
//Check for correct input
if (playSeq.size() > 0 && (playSeq.get(playSeq.size()-1) != compSeq.get(playSeq.size()-1))) {
isRunning = false;
isPlayerTurn = false;
}
}else{
playSeq.clear();
compSeq.clear();
isPlayerTurn = false;
onComputerDown();
}
}
return false;
}
});

How can i make a text in android-studio to be animated?

For example if i display in a TextView the text "Uploading" now i want it to display the text as "Uploading..." and the 3 points to be delete and show again like it's processing doing something and not just static text.
I have this in the MainActivity onTouch event:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (connectedtoipsuccess == true)
{
if (is_start == true)
{
uploadTimerBool = true;
timers.StartTimer(timerValueRecord, "Recording Time: ");
response = Get(iptouse + "start");
is_start = false;
} else
{
timers.StopTimer(timerValueRecord);
textforthespeacch = "Recording stopped and preparing the file to be shared on youtube";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
status1.setText("Preparing the file");
}
});
MainActivity.this.initTTS();
response = Get(iptouse + "stop");
is_start = true;
startuploadstatusthread = true;
servercheckCounter = 0;
}
if (response != null)
{
try
{
a = new String(response, "UTF-8");
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (a.equals("Recording started"))
{
status1.setText("Recording");
}
if (a.equals("Recording stopped and preparing the file to be shared on youtube"))
{
status1.setText("Recording Stopped");
}
}
});
textforthespeacch = a;
MainActivity.this.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
return true;
}
This line:
status1.setText("Preparing the file");
Instead displaying only static text "Preparing the file" i was wondering how to make that it will display something like moving points like "Preparing the file..." then "Preparing the file.." and "Preparing the file." and again "Preparing the file..." then "Preparing the file.." and so on.
Use this awesome library, exactly what you are looking for:
https://github.com/tajchert/WaitingDots
Add this to dependencies
compile 'pl.tajchert:waitingdots:0.2.0'
and you can use the methos. The description is in the link
Handler handler = new Handler();
for (int i = 100; i <= 3500; i=i+100) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(i%300 == 0){
textView.setText("Uploading.");
}else if(i%200 == 0){
textView.setText("Uploading..");
}else if(i%100 == 0){
textView.setText("Uploading...");
}
}
}, i);
}

Using a BoxSelect class inside a runnable method in a thread (java)

This is how I am trying to execute my code.
private final class BoxSelect implements View.OnTouchListener
{
public boolean onTouch(View view, MotionEvent motionEvent)
{
setView(view);
setMotionEvent(motionEvent);
if (t1.getState() == Thread.State.NEW)
{
t1.start();
if (getHit() == false) {
t2.start();
}
}
return false;
}
}
I have two thread created called t1 and t2 which take the two runnable methods r1 and r1 as parameters:
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
R1 is defined as:
Runnable r1 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t1");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
View view1 = getView();
MotionEvent motionEvent1 = getMotionEvent();
public void whenCreate()
{
System.out.println("HERE t1");
hit = false;
boolean goToElse = true;
boolean hit2 = false;
boolean goToElse2 = true;
if (motionEvent1.getAction() == MotionEvent.ACTION_DOWN) {
for (int i = 0; i < ids.length; i++) {
for (int j = 0; j < ids.length; j++) {
String coord = b.getBoard()[i][j];
if (view == ids[i][j]) {
System.out.println("ATTACKING " + b.getCompTempBoard()[i][j]);
player.basicAttack(b.getBoard(), coord, ai);
}
if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("HIT")) {
System.out.println("Hit GUI");
if (ids[i][j].getBackground().equals(hitTarget)) {
hit = true;
goToElse = false;
} else {
ids[i][j].setBackgroundDrawable(hitTarget);
System.out.println("ert 1 " + b.getCompTempBoard()[i][j]);
playerCount++;
if (playerCount == 10) {
player.endGame();
b.incrementPlayerCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU WIN :)\nScore is:\nPlayer: " + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
hit = true;
goToElse = false;
}
} else if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("MISS")) {
System.out.println("MISS GUI 1");
if (ids[i][j].getBackground().equals(missTarget)) {
hit = true;
goToElse = false;
} else {
System.out.println("MISS GUI");
ids[i][j].setBackgroundDrawable(missTarget);
System.out.println("ert 2 " + b.getCompTempBoard()[i][j]);
hit = true;
goToElse = true;
}
}
if (goToElse == true) {
hit = false;
System.out.println("MISS PLAYER GUI");
view.setBackgroundDrawable(missTarget);
}
}
}
}
}
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
}
}
};
and R2 is:
Runnable r2 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t2");
try {
TimeUnit.NANOSECONDS.sleep(1);
System.out.println("HERE 2");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
public boolean onTouch(View view, MotionEvent motionEvent) {
System.out.println("HERE t2");
if (hit == false) {
System.out.println("SLEEPING 2");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("COMPUTERS TURN");
ai.advancedAttack(b.getBoard(), ai.getRandomCoordinate_For_Attacking_6x6(), player);
System.out.println("First attack: " + ai.getFirstCoord());
boolean goAgain = true;
while (goAgain == true) {
for (int w = 0; w < ids2.length; w++) {
for (int y = 0; y < ids2.length; y++) {
if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("HIT")) {
System.out.println("DR 1");
ids2[w][y].setBackgroundDrawable(hitTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
System.out.println("Next: " + ai.getFirstCoord());
ai.advancedAttack(b.getBoard(), ai.getFirstCoord(), player);
System.out.println("After attack in loop");
goAgain = true;
CompCount++;
if (CompCount == 10) {
b.incrementCompCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU LOSE :(\n" + "Score is:\n" + "Player: \n" + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
} else if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("MISS")) {
System.out.println("DR 2");
ids2[w][y].setBackgroundDrawable(missTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
goAgain = false;
}
}
}
}
}
return hit;
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
System.out.println("IN CATCH");
}
System.out.println("END");
}
};`
I originally had these two together as one block, but separated it as I wish to pause thread 2 from occurring for one second after thread 2.
The problem I am having is that the BoxSelect class is not getting executed inside the R1 and R2 and so none of the code is executing. Any help on this matter would be appreciated!

CountDownTimer Android issue

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(...);

Categories

Resources