3

I have a TextView in an XML layout (in an Android application). This TextView displays the value of of a string in strings.xml. However, as my java code runs I want the value of that string to change each second for 4 consecutive seconds and I want the XML layout to show that change.

Is there a way to change the value of the string in strings.xml while the java code runs? If not is there an alternative way to change the text displayed by a textView in a layout as the java code runs?

Uwais A
  • 737
  • 6
  • 23
  • 5
    `Strings.xml` is unchangable. [`TextView#setText()`](http://developer.android.com/reference/android/widget/TextView.html#setText(int)) however, can accept any String/String resource id. – A--C Jan 26 '13 at 20:58
  • Forget layout. http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence). Please also do some basic Java tutorials before you try to develop Android apps. – Simon Jan 26 '13 at 20:58
  • 1
    see [Updating TextView every N seconds?](http://stackoverflow.com/questions/4776514/updating-textview-every-n-seconds) for updating textview when your java code running – ρяσѕρєя K Jan 26 '13 at 20:59
  • @A--C Thanks for the replies - I thought Strings.xml was unchangeable but in another thread someone was saying it could be changed and that was not contested. I tried to used "TextView.setText(num)" where 'num' is the String variable I am displaying but an error appeared saying when I defined TextView it needed to be a 'final' variable. So I did that but that results in the app crashing when it is about to change to the second value of 'num'. Is there a way to allow it to change more than once i.e. before and after a 'sleep(1000);'? or is there something else I'm doing wrong? – Uwais A Jan 26 '13 at 22:05
  • @user2014236 if you're using a plain old `Thread`, you're probably getting an exception saying that you can't update the UI from a different `Thread` (which is why we use [`runOnUIThread()`](http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable))) coder's answer I'd say should work and it's definitely cleaner. – A--C Jan 26 '13 at 22:39

1 Answers1

3

I'd recommend using a Timer.

private Timer timer = new Timer();
private TimerTask timerTask;
timerTask = new TimerTask() {
  @Override
  public void run() {
    //refresh your textview
  }
};
timer.schedule(timerTask, 0, 10000);

You can cancel it using:

timer.cancel();
A--C
  • 36,351
  • 10
  • 106
  • 92
Buneme Kyakilika
  • 1,202
  • 3
  • 13
  • 34