Created clock on Android is not updating - android

I´m trying to create a fullscreen clock. I managed to set text for hours, minutes and seconds. Well, but when I start the app, it shows the time but the UI is not updating... I dont know how to do it, I read this tutorial but i dont understand it... any one can explain me how to consantly update the UI?
public class Clock1Activity extends Activity {
/** Called when the activity is first created. */
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtHour = (TextView)findViewById(R.id.TxtHour);
final TextView txtMinutes = (TextView)findViewById(R.id.TxtMinute);
final TextView txtSeconds = (TextView)findViewById(R.id.TxtSeconds);
final TextView txtMilliseconds = (TextView)findViewById(R.id.TxtMilliseconds);
final Integer hora = new Integer(Calendar.HOUR_OF_DAY);
final Integer minutos = new Integer(Calendar.MINUTE);
final Integer segundos = new Integer(Calendar.SECOND);
final Long milisegundos = new Long (System.currentTimeMillis());
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
// Get the Current Time
final Runnable updateTask = new Runnable() {
public void run() {
/** txtHour.setText(hora.toString());
txtMinutes.setText(minutos.toString());
txtSeconds.setText(segundos.toString()); */
txtMilliseconds.setText(milisegundos.toString());
Toast toast1 = Toast.makeText(getApplicationContext(), milisegundos.toString(), Toast.LENGTH_SHORT);
toast1.show();
}
};
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 1000);
}
}
Just tell me how to complete it to update UI,please...

You didn't mention which tutorial you're working on, so just in case, you'll probably want to use AsyncTask.

see this example for Create a Apps to Show Digital Time in Android .And in your case use
runOnUiThread for Upadting time on UI.as
CurrentActivity.this.runOnUiThread(new Runnable() {
public void run() {
//UPDATE TIME HERE
}
});
and your code look like:
public class Clock1Activity extends Activity {
/** Called when the activity is first created. */
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtHour = (TextView)findViewById(R.id.TxtHour);
final TextView txtMinutes = (TextView)findViewById(R.id.TxtMinute);
final TextView txtSeconds = (TextView)findViewById(R.id.TxtSeconds);
final TextView txtMilliseconds = (TextView)findViewById(R.id.TxtMilliseconds);
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
// Get the Current Time
final Runnable updateTask = new Runnable() {
public void run() {
final Integer hora = new Integer(Calendar.HOUR_OF_DAY);
final Integer minutos = new Integer(Calendar.MINUTE);
final Integer segundos = new Integer(Calendar.SECOND);
final Integer milisegundos = new Integer(Calendar.MILLISECOND);
txtHour.setText(hora.toString());
txtMinutes.setText(minutos.toString());
txtSeconds.setText(segundos.toString());
txtMilliseconds.setText(milisegundos.toString());
}
};
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 1000);
}
}

Related

Update time display every minute, not just on create?

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.

How to update TextView dynamically (periodically)?

I am developing a simple android activity with a scrollable TextView. I am displaying numbers from 1-100 in my TextView with a time delay. However my desired output is not what I'm getting.
Current Output: 1 replaced by 2 replaced by 3....till 100.
Desired Output:
1
2
3
4
.
.
100
Here is my Activity code:
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
textView = (TextView) findViewById(R.id.text_area);
new PrimeCalculation().execute();
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
textView.setText(Integer.toString(i));
i++;
handler.postDelayed(this, 1000);
}
}
};
}
How about this:
textView.setText(textView.getText() + "\n" + i);
Create a new String Array. Set the text view to the array.toString(); Every time that your timer runs out insert the most recent number into the array and repeat. The most recent number should be an int that increases when the timer runs out. Hope this helps!
Try this
private Handler mHandler = new Handler();
private int nCounter = 0;
View.OnClickListener mButtonStartListener = new OnClickListener() {
public void onClick(View v) {
try {
mHandler.removeCallbacks(hMyTimeTask);
// Parameters
// r The Runnable that will be executed.
// delayMillis The delay (in milliseconds) until the Runnable will be executed.
mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable hMyTimeTask = new Runnable() {
nCounter++;
hTextView.append("\n"+nCounter);
}
public void run() {
};
Hope this will help you
You can use following code......
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
String textViewText="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_area);
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
//
textViewText=textViewText+Integer.toString(i)+" ";
textView.setText(textViewText);
// textViewText=textViewText+textView.getText().toString();
i++;
handler.postDelayed(this, 1000);
}
}
};}
I hope it will help you....

Change TextView value every second (Android)

i am creating a sample app in which i want to change a TextVeiw value every second.
TextView value should change continue every second.
to perform this task i tried this below code:
but this code is not changing text values continue, it only change on app start or screen rotate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Boolean b = true;
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
Thread t = new Thread() {
#Override
public void run() {
try {
while (b != false) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update TextView here!
tv.setText(str[random]);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
and i also tried this code:
but this code crash application
private Timer timer = new Timer();
private TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
timerTask = new TimerTask() {
#Override
public void run() {
// refresh your textview
tv.setText(str[random]);
}
};
timer.schedule(timerTask, 0, 1000);
}
Try the following code snippet
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
long millis =(long)currentTime();
dateAndTime.setText(getDate(millis, "dd/MM/yyyy hh:mm:ss.SSS"));
h.postDelayed(this, 1000);
}
});
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "23458", "9654", "987650", };
// //
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
// //

TextView Timer trouble

i'm new to the world of writing code, and I need help with TextView. I want the displayed android time to countdown on the screen eg from 10 to 1. At the minute it's displaying the first number, but it doesn't change. Any help would be greatly appeciated.
private final Handler mHandler = new Handler();
private TextView mTest;
private long startTime = 10 * 1000;
private Runnable mTask = new Runnable()
{
public void run()
{
mTest.setText("Sorry. Times up!");
}//run
};//mTask
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTest = (TextView) findViewById(R.id.timer);
mTest.setText(mTest.getText() + String.valueOf(startTime / 1000));
mHandler.postDelayed(mTask, 10000);
}//onCreate
#Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(mTask);
}//onDestroy
Try this:
TextView mTest;
private final Handler mHandler = new Handler();
private int startTime = 10;
private Runnable mTask = new Runnable()
{
public void run()
{
if(startTime > 0)
{
mTest.setText(String.valueOf(startTime));
startTime--;
mHandler.postDelayed(mTask, 1000);
}
else
{
mTest.setText("Sorry. Times up!");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTest = (TextView) findViewById(R.id.timer);
mHandler.post(mTask);
}

How to make Dynamic change of TextVIew and UI in general?

Good afternoon everyone
So, I'm trying to dynamically change textview's properties.
basically, I defined a Duration. and I want to my handler/runnable to append text to a textView until I reach the duration.
public class Dynamic_testActivity extends Activity
{
public Context context = null;
public TextView view = null;
public Handler mHandler = null;
public long startTime = 0L;
public final int duration_millis = 10000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
view = (TextView) findViewById(R.id.textView1);
view.append("\n");
mHandler = new Handler();
}
#Override
protected void onStart() {
super.onStart();
startTime = System.currentTimeMillis();
mHandler.post(new Runnable() {
#Override
public void run() {
view.append("Hell_yeah_!\n");
// 10 character lenght
}
});
}
}
So yes, it append the text once, because the run do so.
But how could I make some kind of loop, without blocking the UI Thread, and append text until the end of the duration.
That was the first step ...
The second part now ... In fact, I Want to change the color of the text.
using
Spannable WordtoSpan = new SpannableString(view.getText());
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, view.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
I want to the color changing to be dynamic for the duration ... like a karaoke ...
So, is it possible to make that in the runnable without having the UI Thread blocked until the end of the duration ? and How ?
If anyone could explain the complet process ? or post some source code
Solved.
Here is a basic example...
There is still a little trouble ... at the very beginning of the application, the whole textview is yellow, and after a second, it updates the display as it should be .
If any one knows why, advices are welcome =)
Note : there's only two simple Textview in the layout... Duration is in milliseconds... and there is 10 character in the dynamic textview to fit the duration ... So basically, one char = one second ...
public class Dynamic_testActivity extends Activity
{
public Context context = null;
public TextView view = null;
public TextView view2 = null;
public Handler handler = null;
public long start_time, current_time, elapsed_time = 0L;
public final int duration = 10000;
public int end = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
view = (TextView) findViewById(R.id.textView1);
view2 = (TextView) findViewById(R.id.textView2);
handler = new Handler();
}
#Override
protected void onStart() {
super.onStart();
start_time = Long.valueOf( System.currentTimeMillis() );
current_time = start_time;
handler.postDelayed(new Runnable() {
#Override
public void run() {
current_time = Long.valueOf( System.currentTimeMillis() );
elapsed_time = Long.valueOf(current_time) - Long.valueOf(start_time);
if ( elapsed_time >= duration + 30 ) {
Toast.makeText(context, "Done", Toast.LENGTH_LONG).show();
//finish();
} else {
end = (int) (elapsed_time / 1000);
Spannable WordtoSpan = new SpannableString(view.getText());
WordtoSpan.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(WordtoSpan);
view2.setText("time : " + elapsed_time);
handler.postDelayed(this, 10);
}
}
}, 10);
}
}
In your run() methond, you can call mHandler.post(this) (or use postDelayed to delay it)
There is property change animation in API level 14, but if you are targetting a lower version, use postDelayed repetively to change progressively the color of the text.

Categories

Resources