countdowntimer doesn't print on textview - android

my application is question/answer application , the user ask for a question , then the server send question to a user, when user receives the question , a ShowQuestion button appears , when user click it , i want to start timer , because a user have to answer in just 36 Second
i build a textView in my xml like this
<TextView
android:id="#+id/tvRemaingTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
/>
and in my Java activity i make this
TextView remaingTimer;
CountDownTimer timer;
private void initialize() {
remaingTimer=(TextView)findViewById(R.id.tvRemaingTime);
}
and when a user click ShowQuestion i make this
timer =new CountDownTimer(360000,100) {
public void onTick(long millisUntilFinished) {
remaingTimer.setText(millisUntilFinished+"");
}
public void onFinish() {
remaingTimer.setText("finish");
}
};
timer.start();
but it doesn't print anything, what am i doing wrong ?
NOTE
i am using AsyncTask to get question from server like this:
public class getQuestionFromServer extends
AsyncTask<String, Integer, String[]> {}
but i don't thing it effect on textView because the ShowQuestion button will not appear else a user have got a question from the server

you can use runOnUiThread for updateing TextView from Thread as:
TextView remaingTimer;
CountDownTimer timer;
private boolean mClockRunning=false;
private int millisUntilFinished=36;
private void initialize() {
remaingTimer=(TextView)findViewById(R.id.tvRemaingTime);
}
ShowQuestionbutn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mClockRunning==false)
{
mClockRunning=true;
millisUntilFinished=0;
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
while(mClockRunning)
{
Thread.sleep(100L);// set time here for refresh time in textview
CountDownTimerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(mClockRunning)
{
if(millisUntilFinished<0)
{
mClockRunning=false;
millisUntilFinished=36;
}
else
{
millisUntilFinished--;
remaingTimer.setText(millisUntilFinished+"");//update textview here
}
}
};
}
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}

Related

Show ProgressBar for a few seconds in Android

I have to wait some seconds in my Android App and I want to show a progress bar during this time, how can I do this?
for example :
#Override
protected void onCreate(Bundle savedInstanceState) {
timeForShow(5 //second);
}
.
.
.
private void timeForShow(long mytime){
myprogress.setVisibility(View.VISIBLE);
Waiting for mytime...
myprogress.setVisibility(View.GONE);
}
this is my code but it does not work:
Long timerforprogressbar ;
#Override
protected void onCreate(Bundle savedInstanceState) {
timerforprogressbar = (long) 5000 ;
new MyProgressBar().execute((Void)null);
}
.
.
.
class MyProgressBar extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
try {
Thread.sleep(timerforprogressbar);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressbar.setVisibility(View.GONE);
}
}
my progress bar :
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminateDrawable="#drawable/progress" >
</ProgressBar>
progressbar is my progress bar,plz help me,tnx.
For your specific use case it would be simpler to use a Handler:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressbar.setVisibility(View.GONE);
}
}, timerforprogressbar);
You did not mention how your progressbar is constructed but if you simply want an indeterminate progress to show, then constructing it programatically would be the most simple thing to do I think.
private ProgressDialog working_dialog;
private void showWorkingDialog() {
working_dialog = ProgressDialog.show(context, "","Working please wait...", true);
}
private void removeWorkingDialog() {
if (working_dialog != null) {
working_dialog.dismiss();
working_dialog = null;
}
}
That would make the code look like:
showWorkingDialog();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
removeWorkingDialog();
}
}, timerforprogressbar);
You can always use the CountDownTimer:
public void timer() {
countDownTimer=new CountDownTimer(20000, 1000) { //display a delay of 20 seconds
public void onTick(long millisUntilFinished) {
if (somethingToBreakTheCount)
countDownTimer.onFinish();
txtDebug.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
txtDebug.setText("Done!");
finish();
}
}.start();
}
// We can achieve this by using Coroutines.
// Simply start a coroutine and change the progress of progressbar by changing the dispatcher context after few milliseconds.
// Here I am showing the progress for 1 second before moving to next fragment.
CoroutineScope(Dispatchers.IO).launch {
for (i in 0..100) {
delay(10)
withContext(Dispatchers.Main) {
binding.progressBar.progress = i
}
}
//Navigate to next fragment using nav contorller or with Intents for next Activity
navController.navigate(R.id.action_startFragment_to_listFragment)
}
Updating progress dialog in Activity from AsyncTask
There re is a method for async tasks for progress updates.
Here is a link to a better post on it
As a simpler solution than an AsyncTask, you can always look into using a CountDownTimer for this action.
If you are performing a task in AsyncTask doInBackground(), then you can initiate your progressBar in onPreExecute() and disable it in onPostExecute().

How to late thread run in android

In my code I have a thread. You can see the code of thread,
public class MainAsyncHome extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String xml) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
I run this thread in my main activity onCreate method as following way
new MainAsyncHome().execute(null);
But I want to give time out for this thread. It means when main activity run I want late to run this thread. I know it can do using sleep method. But How I can late for running this thread just like that way.
I'm stuck with this problem.
pls give me answer. Thanks
Use Handler class, and define Runnable handleMyAsyncTask that will contain code executed after 3000 msec delay:
mHandler.postDelayed(MainAsyncHome, 1000*3); //Delay of three seconds
The answer is taken from here.
To put it in the code:
private final static int INTERVAL = 1000 * 3; //3 seconds
Handler m_handler;
Runnable MainAsyncHome = new Runnable()
{
#Override
public void run() {
doSomething();
m_handler.postDelayed(MainAsyncHome, INTERVAL);
}
}
void startRepeatingTask()
{
MainAsyncHome.run();
}
void stopRepeatingTask()
{
mHandler.removeCallback(MainAsyncHome);
}
Hope it works.
I normally use CountDownTimer, suppose a 3 seconds of delay:
CountDownTimer timer = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//do things, start your Task
//remember we are still in the main thread!
}
}.start();
Get more info at:
http://developer.android.com/reference/android/os/CountDownTimer.html
Use a CountDownTimer like this.
Start your timer in onCreate.
CountDownTimer timer=new CountDownTimer(Delay,TimeIntervalToCallOnTick) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
//start your asynctask
}
};

How to create timer for doing canvas rendering

public void BetTimerFuction()
{
int delay=0;
int period=200;
betTimer = new Timer();
betTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
mHandlerBet.obtainMessage().sendToTarget();
}
}, delay, period);
}
Its my timer code but i didn't work with that timer in view class i m also using canvas .
When I use that timer in view class that timer get a number prosess is very slow when i click the button its increase the the integer two timers
I think u do the null first for your stop function.
public void StopBetTimer()
{
try
{
if(betTimer !=null)
{
betTimer.cancel();
betTimer=null;
}
}
catch(Exception e)
{
}
}
I revised you code because i think in that code no issue. But may be you didn't initialize properly to null your timer when you use first and also stop properly.
public void BetTimerFuction()
{
int delay=0;
int period=100;
betTimer = new Timer();
betTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
mHandlerBet.obtainMessage().sendToTarget();
}
}, delay, period);
}
Here is for you stop function
public void StopBetTimer()
{
try
{
if(betTimer !=null)
{
betTimer.cancel();
betTimer=null;
}
}
catch(Exception e)
{
}
}

runOnUiThread is not running in AsyncTask

I'm coding a program which fetches the data from MySql from server (using JSON) and it updates the UI accordingly,
I'm fetching two types of data using AsyncTask from Server
1) Bubble Answers
2) Comments
The parseBubbleAnswers method successfully runs and Updates UI,
but parseComments class which is AsyncTask, and which call parseComments method in doInBackground, is not running runOnUiThread(new Runnable() { run() });
Can anyone help me in solving this
Here is my code :
public class FetchServer extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
String photoId = "1"; // photo id for which the data is fetched
checkBubbleData(photoId); // which call AsyncTask - 2 differnt calls
}
public void checkBubbleData(String photoId)
{
new parseBubbleAnswers().execute(photoId); // to fetch bubble answers
new parseComments().execute(photoId); // to fetch comments
}
class parseBubbleAnswers extends AsyncTask<String, Integer,String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
Looper.prepare();
parseBubbleAnswers(); // which has runOnUiThread(new Runnable() which updates (successfully !) the UI
return null;
}
}
class parseComments extends AsyncTask<String, Integer,String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
Looper.prepare();
String parseComReturn = parseComments();
if(parseComReturn=="end")
{
commentBuilder(); // which will update UI after fetch data by parseComments() method
}
}
}
public void commentBuilder()
{
runOnUiThread(new Runnable() // while debugging, it comes here, on Step Over it stick for 2 times and then move at the end of method without error
{
public void run()
{
// update UI code
}
});
}
}
Try this way :
First create one Handler :
Handler mHandler = new Handler();
Change this,
public void commentBuilder()
{
runOnUiThread(new Runnable() // while debugging, it comes here, on Step Over it stick for 2 times and then move at the end of method without error
{
public void run()
{
// update UI code
}
});
}
With,
public void commentBuilder()
{
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
Stop thread by this once you are done with UI,
isRunning = false;
EDIT :
Try to Use Async Task in this way :
class parseComments extends AsyncTask<String, Integer,String>
{
protected String doInBackground(String... params) {
String parseComReturn = parseComments();
return parseComReturn;
}
protected void onPostExecute(String result) {
if(result.equals("end"))
{
commentBuilder();
}
}
}
Thanks.
runOnUiThread is a method of Activity, AsyncTask has no reference to Activity.
however, AsyncTask already runs on the UI thread and was designed to do exactly that.
just deal with the UI changes in onPostExecute.
I faced the similar issue.
Just pass the reference of the Activity class to the parseComments class.
class parseComments extends AsyncTask<String, Integer,String>{
Activity activity;
public parseComments(Activity activity){
this.activity = activity;
}
}
After that you can use runOnUiThread as
activity.runOnUiThread(new Runnable(){
#Override
public void run(){
}
});
It will only work with Activity class. Not Context class.

how to include timer in my program?

i need to include timer in my application.i just gone through the example given in the sites.and tried to implement that in my program.but the thing is i dont know how to work with timer.in my program i want to start the timer on a button click.timer has to show in the screen.but the screen is a canvas(when we click on button it loads a canvas) with moving objects.when two objects collide timer has to stop and has to show the value in a message box.given below is my main activity code.
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
public static Timer myTimer;
private Button startbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startbtn=(Button)findViewById(R.id.startbtn);
startbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// set our MainGamePanel as the View
setContentView(new MainGamePanel(getApplicationContext()));
Log.d(TAG, "View added");
}
});
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
#Override
protected void onDestroy() {
Log.d(TAG, "Destroying...");
super.onDestroy();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopping...");
super.onStop();
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
i know how to check collision.i need only timer part like starting timer,showing on the screen and stopping it from another class.can anybody help me...plz....
Use this the code will be repeated after one second and timer will run for 30sec
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
}
}.start();

Categories

Resources