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();
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();
}
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?
i have made a countdown timer using progressbar and a thread,Now i want to stop the progress at the same time when user clicks on a button.I have tried thread.stop(),but it says there is .no such method,I have tried interruot method too with no luck,So can any buddy please help me by viewing my code.My code is as below:
code
package com.amar.lyricalgenius;
import com.amar.lyricalgenius.LoadingActivity.MyCountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SinglePlayerOption extends Activity implements OnClickListener {
// visible gone
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
TextView text_player_second;
ImageView vs_word;
ImageView player_second_pic, player_second_box;
ImageButton red_point1;
TextView text_number_pt1;
TextView text_number1;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.single_player_option);
init();
}
private void init() {
// TODO Auto-generated method stub
text_player_second = (TextView) findViewById(R.id.text_player_second);
vs_word = (ImageView) findViewById(R.id.vs_word);
player_second_pic = (ImageView) findViewById(R.id.player_second_pic);
player_second_box = (ImageView) findViewById(R.id.player_second_box);
red_point1 = (ImageButton) findViewById(R.id.red_point1);
text_number_pt1 = (TextView) findViewById(R.id.text_number_pt1);
text_number1 = (TextView) findViewById(R.id.text_number1);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
text_player_second.setVisibility(View.GONE);
vs_word.setVisibility(View.GONE);
player_second_pic.setVisibility(View.GONE);
player_second_box.setVisibility(View.GONE);
red_point1.setVisibility(View.GONE);
text_number_pt1.setVisibility(View.GONE);
text_number1.setVisibility(View.GONE);
countDownTimer = new MyCountDownTimer(startTime, interval);
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
splashThread = new Thread() {
public void run() {
try {
sleep(6000);
// Utils.systemUpgrade(SplashActivity.this);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = null;
intent = new Intent(SinglePlayerOption.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
};
splashThread.start();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.option_1:
splashThread.stop();
countDownTimer.onFinish();
Toast.makeText(SinglePlayerOption.this,
timer_text.getText().toString(), 1).show();
i = new Intent(SinglePlayerOption.this,
DialogLeaderboardActivity.class);
startActivity(i);
break;
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timer_text.setText("Time's up!");
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
}
Thread th = new Thread(new Runnable() {
public void run() { ....
th.start();//starts
th.interrupt();//this stops.
and use
while (progressStatus < 100 && (!Thread.currentThread().isInterrupted())){....
instead of
while (progressStatus < 100) {....
Now i want to stop the progress at the same time when user clicks on
a button.I have tried thread.stop()
Thread.stop() is deprecated and you should not use it. The basic concept to understand is that a thread terminates is execution when the last line of code of his run method is executed. In the case of your "ProgressBar Thread*, when the user press the button, you have to set the exit condition of your while-loop (progressStatus = 100) in order to make it terminate
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.
package com.aviyehuda.test.multithreading;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MultithreadingTest extends Activity {
Button btn;
private Handler myHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.Button01);
}
public void buttonClicked(View v) {
myHandler = new Handler();
MyThread mThread = new MyThread();
mThread.start();
}
class MyThread extends Thread {
#Override
public void run() {
for (int i = 0; i < 30; i++) {
myHandler.post(new NewThreaad(i));
}
}
}
class NewThreaad implements Runnable{
int i;
public NewThreaad(int n) {
i=n;
}
#Override
public void run() {
((TextView) findViewById(R.id.TextView01)).setText("Hello:"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have code mentioned above but getting result Hello29 on TextView but i want Hello1,Hello2,hello3.................Hello29 one by one automatically
Please give me hint what I am doing wrong
A couple of things.
First, after changing the text, you should call invalidate on the TextView to force a refresh.
Second, to do operation on the UI, you should run that in the UI thread. Use runOnUiThread
Well, the main problem is that you're not appending you are overwriting. Instead of
((TextView) findViewById(R.id.TextView01)).setText("Hello:"+i);
do
TextView tv = ((TextView) findViewById(R.id.TextView01));
String text = tv.getText().toString();
tv.setText(text + " Hello:" + i);
You need to move the 500 ms delay to your for-loop, between posting of messages. I think you're expecting the messages to execute sequentially one after the other, but they don't, which is the reason you just see the result of the last one.