how to change text in Android TextView

Your onCreate() method has several huge flaws:

1) onCreate prepares your Activity – so nothing that you do here will be made visible to the user until this method finishes! For example – you will never be able to alter a TextView‘s text here more than ONE time as only the last change will be drawn and thus visible to the user!

2) Keep in mind that an Android program will – by default – run in ONE thread only! Thus: never use Thread.sleep() or Thread.wait() in your main thread which is responsible for your UI! (read “Keep your App Responsive” for further information!)

What your initialization of your Activity does is:

  • for no reason you create a new TextView object t!
  • you pick your layout’s TextView in the variable t later.
  • you set the text of t (but keep in mind: it will be displayed only after onCreate() finishes and the main event loop of your application runs!)
  • you wait for 10 seconds within your onCreate method – this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)
  • then you set another text – this one will be displayed as soon as your onCreate() method finishes and several other Activity lifecycle methods have been processed!

The solution:

  1. Set text only once in onCreate() – this must be the first text that should be visible.

  2. Create a Runnable and a Handler

    private final Runnable mUpdateUITimerTask = new Runnable() {
        public void run() {
            // do whatever you want to change here, like:
            t.setText("Second text to display!");
        }
    };
    private final Handler mHandler = new Handler();
    
  3. install this runnable as a handler, possible in onCreate() (but read my advice below):

    // run the mUpdateUITimerTask's run() method in 10 seconds from now
    mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
    

Advice: be sure you know an Activity‘s lifecycle! If you do stuff like that in onCreate()this will only happen when your Activity is created the first time! Android will possibly keep your Activity alive for a longer period of time, even if it’s not visible!
When a user “starts” it again – and it is still existing – you will not see your first text anymore!


=> Always install handlers in onResume() and disable them in onPause()! Otherwise you will get “updates” when your Activity is not visible at all!
In your case, if you want to see your first text again when it is re-activated, you must set it in onResume(), not onCreate()!

Leave a Comment