I Have countDownTimer() method and want to print a certain toast if the user presses the button when the timer is at 10 or 9 seconds left. I am trying to read the time by reading the textview of the timer in the gameButton() method but it only prints the fail toast and not the pass toast. So why can I not do this? And also how can I get it to work? Thanks.
import android.app.Activity;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class GameScreen extends Activity {
private TextView time;
private Button start;
private Button cancel;
private Button gameButton;
private CountDownTimer countDownTimer;
private View.OnClickListener btnClickListener = new View.OnClickListener(){
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_ID :
start();
break;
case R.id.cancel :
cancel();
break;
case R.id.gameButton_ID :
gameButton();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
start = (Button) findViewById(R.id.start_ID);
start.setOnClickListener(btnClickListener);
cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(btnClickListener);
time = (TextView) findViewById(R.id.time);
gameButton = (Button) findViewById(R.id.gameButton_ID);
gameButton.setOnClickListener(btnClickListener);
}
public void start(){
time.setText("15");
countDownTimer = new CountDownTimer(15 * 1000, 1000) {
#Override
public void onTick(long millsUntilFinished){
time.setText("" + millsUntilFinished / 1000);
/* gameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//if(time.getText() == "10" || time.getText() == "9" ){
Toast.makeText(new GameScreen(), "This is my Toast message!", Toast.LENGTH_LONG).show();
//}
}
}); */
}
public void onFinish(){
time.setText("Done !");
}
};
countDownTimer.start();
}
private void cancel(){
if(countDownTimer != null){
countDownTimer.cancel();
countDownTimer = null;
}
}
private void gameButton(){
if(time.getText() == "10" || time.getText() == "9" ){
Toast.makeText(getApplicationContext(), "PASS", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "FAIL", Toast.LENGTH_SHORT).show();
}
}
}
Use equals method not == operator
time.getText().equals("10") || time.getText().equals("9")
See What is the difference between == vs equals() in Java?
Related
This is the line i want to repeat.
handler.postDelayed(runnableCode, 1);
This app is a tycoon app and so the user can buy upgrades and if they tap the button the get $$ and so when they buy upgrades keeping the value up-to-date is required.
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int Test = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler.postDelayed(runnableCode, 1);
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
finish();
}
});
}
public int ButtonCounter(int Counter){
Counter+=1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter+=add;
return Counter;
}
public void Display(int Counter, TextView myTextView) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
// Do something here on the main thread
Counter = AutoCounter(Counter,Test);
Display(Counter, myTextView);
}
};
}
handler.postDelayed(runnableCode, 1);
call that line inside onResume() method. Make sure your show an AlertDialog to the user whenever he or she hits the button to get $$. Since the AlertDialog pops up everytime the user tries to buy $$. onResume() will be called.
Try this
private void startAnimation() {
countDownTimer = new CountDownTimer(700, 500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
//your code to repeat
}
start();
}
}.start();
}
This is a part of an app that I am trying to make. I am trying to make a delay that can be set by the user so after each +1 it delays with 500 milliseconds, but soon I figured that i don't even know how to add a simple build in delay, I tried with delay(1000); it gave me Can not resolve method delay(int) then with sleep(1000); same error, then with TimeUnit.SECONDS.sleep(1); and Thread.sleep(1); nothing worked I am missing something fundamental, maybe I need to import something ? this is the whole program
if (v == swt1){
while (counter<2100000000) {
counter++;
}
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.BLACK);
}
Activity:
package counter.test.my.simplecount;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
Button btn2;
Button btn3;
Switch swt1;
TextView textTitle;
EditText scoreText;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.button);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
swt1 = (Switch)findViewById(R.id.switch1);
scoreText = (EditText)findViewById(R.id.editText);
textTitle = (TextView)findViewById(R.id.textView);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 34);
}
#Override
public void onClick(View v) {
if (v == btn1){
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.CYAN);
}
if (v == btn2){
counter--;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
if (v == btn3){
counter = 0;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
if (v == swt1){
while (counter<2100000000) {
counter++;
}
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
}
}
}
You can use Handler() for delay like
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Your Aftre delay code
}
},500);
Remember to import this:
import android.os.Handler;
Use the "Handler" with "Runnable" to auto increment a value continuously at some time delay. Here i used "1sec" time dealy.
Find below code snippet for your requirement.
Runnable runnable;
Handler handler;
int delayTimeSec = 1000; //1 Sec
handler = new Handler();
runnable = new Runnable(){
#Override
public void run() {
// Your auto increment logic...
handler.postDelayed(runnable, delayTimeSec);
}
}
handler.postDelayed(runnable, delayTimeSec);
Use thread instead of handler if you have got background tasks.
new Thread(new Runnable() {
#Override
public void run() {
///background calculations
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//main thread task to update user interface
}
});
}
}).start();
I try to code a CountDownTimer which can be repeated several times. My code works fine... But just one time. I don't understand why the repeated action is not done :-(
Here is my code :
package com.bigmat.MyTimer;
import android.app.Activity;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.*;
public class MainActivity extends Activity {
private TextView inputDuration;
private TextView tvCdTimer;
private Button start;
CountDownTimer myCdTimer;
NumberPicker npDuration;
CheckBox isRepeat;
TextView tvRepeat;
int nbRepeat;
int count;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputDuration = (TextView) findViewById(R.id.tvInputDuration);
tvCdTimer = (TextView) findViewById(R.id.tvCdTimer);
start = (Button) findViewById(R.id.btStart);
npDuration = (NumberPicker) findViewById(R.id.npDuration);
npDuration.setMaxValue(60);
npDuration.setMinValue(0);
isRepeat = (CheckBox) findViewById(R.id.cbRepeat);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count=0;
tvRepeat = (TextView) findViewById(R.id.nbRepeat);
if (tvRepeat.getText().toString().length() > 0) {
nbRepeat = Integer.parseInt(tvRepeat.getText().toString());
} else {
nbRepeat = 1;
}
runTimer();
}
});
}
public void runTimer(){
Log.i("CDT", "value of npDuration is : "+npDuration.getValue());
if (npDuration.getValue() > 0 && nbRepeat > 0) {
// create a timer
myCdTimer = new CountDownTimer(npDuration.getValue()*1000, 1000) {
public void onTick(long millisUntilFinished) {
tvCdTimer.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
tvCdTimer.setText("Done ! ");
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
count++;
//condition
if (count < nbRepeat) {
Log.i("MyTimer", "value of nbRepeat :" + nbRepeat + " value of count : " + count);
myCdTimer.cancel();
myCdTimer.start();
}
}
}.start();
} else {
Toast.makeText(getApplicationContext(), "Timer is set on 0 seconds !!!", Toast.LENGTH_LONG).show();
}
}
}
Thanks in advance!
I am having problem in stopping a CountDownTimer. I have searched a lot but couldn't understand how to do that.
Below is my MainActivity. How can I stop the timer if RadioButton b is pressed?
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView mTextField;
RadioButton a, b, c, d, e;
final static long interval = 1000;
long timeout = 15000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextField = (TextView) findViewById(R.id.tv);
a = (RadioButton) findViewById(R.id.rB1a);
b = (RadioButton) findViewById(R.id.rB2a);
c = (RadioButton) findViewById(R.id.rB3a);
d = (RadioButton) findViewById(R.id.rB4a);
e = (RadioButton) findViewById(R.id.rB5a);
//Timer timer = new Timer();
//timer.scheduleAtFixedRate(task, interval, interval);
TimerTask task = new TimerTask() {
#Override
public void run() {
timeout = timeout - interval;
if (timeout == 0) {
this.cancel();
displayText("finished");
return;
}
if (timeout >= 0) {
displayText("time remaining: " + String.valueOf(timeout / 1000));
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "Wrong Answer!!! ", Toast.LENGTH_LONG).show();
Intent openWordlist = new Intent("com.example.the_vocab_master.AA");
startActivity(openWordlist);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "GREAT...!!! ", Toast.LENGTH_LONG).show();
}
});
}
//displayText("time remaining: " + String.valueOf(timeout / 1000));
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, interval, interval);
}
private void displayText(final String text) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
mTextField.setText(text);
}
});
}
}
To cancel the timer use
timer.cancel();
in your onClick listener. It's very difficult to see in your code, because the indentation is very bad, but I think you need to declare your timer variable in the class, instead of in onCreate();
Additionally, I'd suggest you to take both setOnClickListener calls OUTSIDE of the timer run() method. What you're doing doesn't make sense.
I tried to set TTS's paras such as pitch and speech rate by pressing a button, but somehow nothing changes when I pressed it...
See the code following, what I planned is that once I press the button SetPara, the _pitch and _rate will be set to 0.5, and
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
will set TTS's pitch and speech rate to 0.5, but the problem now is that after I pressed the SetPara button the pitch and speech rate didn't change...
Please help me out :))))
package com.example.text2speechtrail;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
private Button btnSetPara;
private EditText getPitch;
private EditText getRate;
public float _pitch;
public float _rate;
String _string_pitch = null;
String _string_rate = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
btnSetPara = (Button) findViewById(R.id.setPara);
txtText = (EditText) findViewById(R.id.txtText);
getPitch = (EditText) findViewById(R.id.getPitch);
getRate = (EditText) findViewById(R.id.getRate);
btnSetPara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SetPara();
}
});
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
public void SetPara(){
_pitch = (float) 0.5;
_rate = (float) 0.5;
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You need to set on click listener for your btnSetPara button
btnSetPara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SetPara();
}
});
You do not need the param View in setPara
public void SetPara(){
_pitch = (float) 0.5;
_rate = (float) 0.5;
if (tts != null) {
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}