Update time display every minute, not just on create? - android

I want the activity time to update every minute, not just on create. This is the code I have so far:
public class MainActivity extends ActionBarActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimeZone tz = TimeZone.getTimeZone("Atlantic/St_Helena");
Calendar c = Calendar.getInstance(tz);
String timez = String.format("Year "+"%02d" , c.get(Calendar.YEAR))
// Display formattedDate value in TextView
TextView time = new TextView(this);
time.setText("Its"+timez+" PM"+"\n\n"+"Ants stretch when they wake up in the morning.");
time.setGravity(Gravity.TOP);
time.setTextSize(20);
setContentView(time);
}}

Try to use a runnable and a handler like this:
handler=new Handler();
new Runnable() {
public void run() {
c = Calendar.getInstance(tz);
timez = String.format("Year "+"%02d", c.get(Calendar.YEAR));
time.setText("Its"+timez+" PM"+"\n\n"+"Ants stretch when they wake up in the morning.");
time.setGravity(Gravity.TOP);
time.setTextSize(20);
setContentView(time);
handler.postDelayed(this, 60000);
}
}.run();

This is the code i have so far
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
},0,1000);
What i want to do is replace the ,0,1000); at the end with something like 60 minutes - current time.

Related

How can i change a textView's content each day at specific time automatically?

I have a List of quotes and i want to show a random quote from that List each day in the morning automatically. I want to implement that in a TextView inside a fragment. I played with the Calendar class but it doesnt work automatically because the instance is created only when the user opens the app. Any suggestion or help to do that with kotlin please!
In your onCreate start a timer (https://developer.android.com/reference/java/util/Timer) with scheduleAtFixedRate(TimerTask task, long delay, long period)
set delay to the time until 00:00. And the period to one day. In the task you can update the textview. Hope that helps. If you have trouble with implementing this, I would be happy to help you.
Here is the code. Havent tested it but should work.
public class MainActivity extends AppCompatActivity {
final Timer t = new Timer();
final long ONE_DAY = 24 * 60 * 60 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateTextView();
}
#Override
protected void onStart() {
super.onStart();
// construct tomorrow midnight
Calendar date = new GregorianCalendar();
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
date.add(Calendar.DAY_OF_MONTH, 1);
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
updateTextView();
}
});
}
}, date.getTime(), ONE_DAY);
}
#Override
protected void onStop() {
super.onStop();
t.cancel();
t.purge();
}
private void updateTextView() {
//... do your update here
}
}

Handler Runnable runs even after activity exit

I am updating the text user types in a textview to database every 5 seconds.
The handler collects data from textview and save it to database.
But the update code runs even after I press back button and return to MainActivity.
How can I stop running the code after exiting from activity.
public class CreateBoxActivity extends AppCompatActivity {
Long current_BoxID = null, parent_BoxID = null;
Handler h=new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_box);
h.post(new Runnable(){ //Run this every five seconds to update the data
#Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String editeddate = sdf.format(Calendar.getInstance().getTime());
String titleText = ((EditText)findViewById(R.id.new_box_title)).getText().toString();
String descriText = ((EditText)findViewById(R.id.new_box_descri)).getText().toString();
Boxes nbx = new Boxes(1, null , titleText, descriText, editeddate, editeddate);
BoxesController.UpdateBox(nbx);
h.postDelayed(this,5000);
}
});
}
You need to release the handler resource when the activity is destroyed.
#override
protected void onDestroy() {
super.onDestroy();
h.removeCallbacksAndMessages(null);
h = null;
}
Create runnable outside of the method like :
Runnable runnable =new Runnable() {
#Override public void run() {
}
};
On your activity's onPause call:
h.removeCallback(runnable);
You can remove the handler in onPause
Runnable runnable =new Runnable() {
#Override public void run() {
}
};
new Handler().removeCallbacks(runnable);

How Automatically Countdown Timer in Android?

I'm working with timer function in Android, I have the code of 1 to up timer. Please help me make it a countdown timer without clicking a button?
public class MainActivity extends Activity {
public int time = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(time));
time += 1;
}
});
}
}, 0, 1000);
}
You can use CountDownTimer for this
new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilEnd) {
mTextView.setText(String.valueOf(millisUntilEnd / 1000));
}
public void onFinish() {
mTextView.setText("done");
}
}.start();
This will update your time TextView each second for 20 seconds.

Updating a textview that shows current time every second or minute

Hi Iam trying to update 3 textviews every second. I have written this piece of code. the thread starts normally but the textviews they do not get updated. I am passing a function inside the text parameters of the texts views that gets the current system time (using Calendar) in digits but then converts it to letters. example: for 3.45 THREE FORTYFIVE. any help would be appreciated. thanks
public class MainActivity extends Activity {
TextView currentv;
GetDate gd;
TextView currentmin;
TextView currentmins;
private Handler mHandler;
private boolean Running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentv = (TextView) this.findViewById(R.id.tvtimehour);
currentmin = (TextView) findViewById(R.id.tvtimemin);
currentmins = (TextView) findViewById(R.id.tvtimesecond);
gd = new GetDate();
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
mHandler = new Handler();
Runnable runb = new Runnable(){
#Override
public void run(){
while(Running == true){
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
mHandler.post(new Runnable(){
#Override
public void run(){
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
};
new Thread(runb).start();
}
Try this,
private MyTimerTask mytask;
private Timer timer;
mytask = new MyTimerTask();
timer = new Timer();
timer.schedule(mytask, 0,60000);
Timer class:
class MyTimerTask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// Do your stuff here it will work
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
Use Timer for this, I think because Thread can not update your UI.

TimerTask doesn't take effect

Here's my code:
public class SomeName extends MapActivity implements OnClickListener, OnTouchListener{
public Timer t1 = new Timer();
public TimerTask tt;
public long interval = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.map);
timer();
}
public final void timer()
{
t1 = new Timer();
tt = new TimerTask() {
#Override
public void run() {
systemClick();
}
};
t1.scheduleAtFixedRate(tt, 10000, interval);
}
public void systemClick()
{
Toast.makeText(getApplicationContext(),"System Button Clicked", 5).show();
}
Actually, I want to call some function, where I refresh my location.
But I can't understand why I never get the toast on the screen.
I'm new to android.
Thanks for any help.
use handler in your Activity
final Handler handlerforadd = new Handler();
Runnable runnableforadd = new Runnable() {
#Override
public void run() {
handlerforadd.postDelayed(this, 1000);
}
};
handlerforadd.postDelayed(runnableforadd, 0);
The reason is the Toast has to be done on the UI thread. In your current code the method run() is being executed on a separate thread. I would suggest looking at this article on Processes and Threads. #parag is correct using a Handler is one way to get a reference to the UI thread but there are other methods.

Categories

Resources