简体   繁体   中英

Updating a textview periodically in android

I'm currently developing an android application. It needs to update a textview value periodically.

For instance, I want to increase the value by 10 each second. I tried with the following code, but it is not working fine : the textview is only updated after the increment is finished

package com.example.stack1;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity{
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    }
    public void onResume(){
        super.onResume();
        TextView output=(TextView) findViewById(R.id.output);
        output.setText(String.valueOf(0));
        System.out.println(0);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        output.setText(String.valueOf(10));
        System.out.println(10);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        output.setText(String.valueOf(20));
        System.out.println(20);
    }
}

output is a textview in main.xml file. This file only contains this object.

Note- Expected output in textview is "0", after 10 second "10" after 20 seconds "20". However, with this code, the output is blank until 20 seconds , then "20" appears.

You'll probably want to use something like AlarmManager instead of sleep() as sleep() will stop everything going on in the process during the sleep time.

The reason it's not showing anything is that you're doing it in the onResume() method. So when it loads up the display, before it actually shows anything, it's processing that method to get things set up for the user.

So, what you want is:

  1. Load display with value 0
  2. Wait 10 seconds
  3. Increment and display to user
  4. Wait 10 seconds
  5. Increment and display to user

What you're getting because of the sleep() commands is:

  1. Set value to 0
  2. Wait 10 seconds
  3. Set value to 10
  4. Wait 10 seconds
  5. Set value to 20
  6. Display value

With an AlarmManager, you initialise that in your onResume() method, the display loads, then the AlarmManager increments the value every ten seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM