I got a problem with CountDownTimer's StartButton: the timer doesn't start after pressing the button. How do I fix that?
I want to start the timer by pressing button buttonCount.
Can someone help me please?
int clicks = 0;
TextView textCount;
ImageButton buttonCount;
int guessCount =0;
boolean started = false;
boolean timerProcessing = false;
private CountDownTimer count;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
count = new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView) findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
if(!started){
count.start();
started = true;
timerProcessing = true;
}
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
}
It seems to me this is what you really want to do:
private int clicks = 0;
private TextView textCount;
private ImageButton buttonCount;
private int guessCount = 0;
private CountDownTimer count; // RENAMED
private boolean started = false; // FALSE.
private boolean timerProcessing = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newgame);
count = new CountDownTimer(15000, 1000) { // MOVED UP
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore)
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
};
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
final TextView textView = (TextView) findViewById(R.id.applesEaten);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("Clicks: " + clicks);
TextView textView = (TextView) findViewById(R.id.topScoreView);
textView.setText("Best: " + oldscore);
if(!started){
count.start(); // START COUNTDOWN TIMER
started = true;
timerProcessing = true;
}
}
});
final TextView textic = (TextView) findViewById(R.id.textView2);
}
And if you really want to start another CountDownTimer than the one you create at the bottom (named count). Then you need to instantiate it and set its behaviour, just like you do for the other CountownTimer.
Also, all the variables you use need to be created before (textic, oldscore)
Related
I want the app to vibrate accordingly to the light value detected. For example, when the value is higher then the vibration is stronger. But this code seems not working, anyone can help to see where is my mistake? It can detect the light value correctly and the vibration is working but the vibration is not vibrating according to the light value.
public class LightDetection extends AppCompatActivity {
TextView textLight, textOn, textOff;
Button btnStart, btnStop;
float x;
long ambientValue = 16;
long floor_delay = 500;
long ceiling_delay = 80;
long vibrate = 100;
long vibrate_delay;
Vibrator sensorVibrator;
SensorManager sensorManager;
Sensor sensor;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_detection);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
textLight = (TextView) findViewById(R.id.textView);
textOn = (TextView) findViewById(R.id.textView2);
textOff = (TextView) findViewById(R.id.textView3);
btnStart = (Button) findViewById(R.id.button3);
btnStop = (Button) findViewById(R.id.button4);
final SensorEventListener lightListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) {
}
#SuppressLint("SetTextI18n")
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
Log.i("IE LightDetect.", "Light value: " + x);
textLight.setText((int) x + " lux");
}
};
btnStart.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
sensorManager.registerListener(lightListener, sensor,
SensorManager.SENSOR_DELAY_FASTEST);
handler.postDelayed(runnable, vibrate_delay);
textOn.setText("LIGHT DETECTION MODE: ON");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
textOn.setText("LIGHT DETECTION MODE: OFF");
sensorManager.unregisterListener(lightListener);
sensorVibrator.cancel();
handler.removeCallbacks(runnable);
}
});
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
long luxValue = (long) x;
//Correction Ratio - Ceiling Delay/Most Likely Max Lux
long ratio = 950 / 300;
if (luxValue < ambientValue) {
vibrate = 100;
vibrate_delay = floor_delay + (ratio * luxValue);
} else {
vibrate = 100;
vibrate_delay = floor_delay - (ratio * luxValue);
}
if (vibrate_delay < ceiling_delay) {
long[] pattern = {0, vibrate, ceiling_delay};
sensorVibrator.vibrate(pattern, 1);
} else {
long[] pattern = {0, vibrate, vibrate_delay};
sensorVibrator.vibrate(pattern, 1);
}
Log.i("IE LightDetect.", "Lux: " + luxValue);
handler.postDelayed(this, vibrate_delay);
}
};
}`
After getting the light value in onSensorChanged() you are not saving the value globally, there u r using float x = event.values[0] which is just creating a local variable inside the function, and not the global one..try ditching the float from there, use x = event.values[0] instead of float x = event.values[0]..the it will save the value in the global variable and that you will use where you calculating vibration..
"goClicked" function is a onClick function to the button "Go" but it is not executing when I click on the button "Go"( I am able to say this because the toast is not appearing ) until I comment the while loop in "goClicked" function. I am pasting the code for only 2 functions "goClicked" and "countdown" because they are the only functions that alter the variable "counterRunning".
public void goClicked(View view) {
afterGoPressed();
countDown();
correctCount = 0;
totalCount = 0;
TextView time = (TextView) findViewById(R.id.time);
while (counterRunning) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
}
public void countDown() {
counterRunning = true;
final TextView time = (TextView) findViewById(R.id.time);
final Button tryAgain = (Button) findViewById(R.id.tryAgain);
final TextView result = (TextView) findViewById(R.id.result);
final TextView score = (TextView) findViewById(R.id.score);
int secondsLeft = 30;
time.setText(secondsLeft+"");
CountDownTimer countDownTimer = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
time.setText(millisUntilFinished/1000 + "");
}
#Override
public void onFinish() {
tryAgain.setVisibility(View.VISIBLE);
result.setText("Your score: " + score.getText());
result.setVisibility(View.VISIBLE);
counterRunning = false;
}
}.start();
}
It is because you're using an infinite loop with the following code:
while (counterRunning) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
the code will blocking all other instruction until it found the counterRunning is changed to false inside the while block. But it never happened. Hence the infinite loop.
public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.
Hello im working with an jumpingApp that will count how many times you are jumping and im using accelorometer sensor.
The problem i got is that i don't really know how to put the delay so it is perfect, sometimes a jump counts as 2 jump sometimes it doesn't register and sometimes it works good. I would like to have around 0.4sec on every count jump.
private TextView textView;
private TextView text;
private SensorManager sensorManager;
double ax,ay,az;
boolean newJumpAccepted = true;
int numbersOfJumps = 0;
long startTime = 0;
int count;
MediaPlayer mediaPlayer;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
if(millis>400){
newJumpAccepted = true;
} else {
newJumpAccepted = false;
}
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerHandler.postDelayed(this,500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
#Override
public void onSensorChanged(SensorEvent event){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String result = "";
double d = Math.round(event.values[1]);
float threshold = preferences.getFloat("hello", 11);
if (d != 0 && d >= threshold && newJumpAccepted){
count++;
}
Log.i("hej", String.valueOf(d));
text.setText("Jump made" + " " + count + " " + d);
text.invalidate();
startTime();
}
private void startTime() {
if(newJumpAccepted) {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
newJumpAccepted = false;
}
}
Timer timer;
MyTimerTask myTimerTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
text = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.textView);
if(timer != null){
timer.cancel();
}
timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 400, 400);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!newJumpAccepted) {
text.setText(String.valueOf(count));
newJumpAccepted = true;
}
}
});
}
}
I wrote a timer code. the clear function doesn't clear the time value (when I press clear only the text changes, but the time value continues form stop point) here is the code, any suggestions to activate the clear button?:
public class MainActivity extends Activity {
private Button startButton;
private Button stopButton;
private Button clearButton;
private TextView timeValue;
private long timeStart = 0L;
private Handler timeHandler = new Handler();
long timeInMilisec = 0L;
long timeMemo = 0L;
long timeUpdate = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeValue = (TextView) findViewById(R.id.timeValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeStart = SystemClock.uptimeMillis();
timeHandler.postDelayed(updateTimerThread, 0);
}
});
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeMemo += timeInMilisec;
timeHandler.removeCallbacks(updateTimerThread);
}
});
clearButton = (Button) findViewById(R.id.clearButton);
clearButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton:
timeValue.setText("00:00:00");
int secs = 0;
int mins = 0;
secs = 0;
int milliseconds = 0;
timeInMilisec = SystemClock.uptimeMillis() - timeStart;
timeUpdate = timeMemo + timeInMilisec;
timeValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
timeHandler.removeCallbacksAndMessages(updateTimerThread);
timeValue.setText("00:00:00");
break;
}
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilisec = SystemClock.uptimeMillis() - timeStart;
timeUpdate = timeMemo + timeInMilisec;
int secs = (int) (timeUpdate / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (timeUpdate % 1000);
timeValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
timeHandler.postDelayed(this, 0);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You should reset the timeMemo variable.
clearButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton:
// Clear the timestart and timeMemo
timeMemo = 0L;
timeValue.setText("00:00:00");
int secs = 0;
int mins = 0;
secs = 0;
int milliseconds = 0;
timeInMilisec = SystemClock.uptimeMillis() - timeStart;
timeUpdate = timeMemo + timeInMilisec;
timeValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
timeHandler.removeCallbacksAndMessages(updateTimerThread);
timeValue.setText("00:00:00");
timeHandler.removeCallbacks(updateTimerThread);
break;
}
}
});
In the ClearButton onClick you are not reseting the value of the "timerstart" and "timeMemo" variables. That is why only the text is being updated but the timer is not being reset.