简体   繁体   中英

Simple way to update an Activity UI in android

I have a simple main activity with 3 buttons, and a background service that runs when Wifi connection is detected. My main activity polls the database on onCreate and displays the status. What i want is to force an Activity to redraw that textview every few second. I dont want to use binders or connect to service. Just some simple way to ask database every few second for a status.

Here is my code.

mdbHelper.open();
Cursor cursor = mdbHelper.fetchAllArticles();
first = cursor.getCount();
cursor = mdbHelper.fetchAllFeeds();
second = cursor.getCount();
cursor.close();
mdbHelper.close();

myTextView.setText(first + " in articles and "  + second + " in feeds.");

I can't seem to update myTextView from any other method except in onCreate...

Thanks!

You can do something like.

private Handler mHandler = new Handler() {
    void handleMessage(Message msg) {
        switch(msg.what) {
            case UPDATE_TEXTVIEW:
            // update the text view;
        }
    }
}

public void onCreate() {
    Thread t = new Thread(new Runnable() {
        void run() {
            mHandler.sendEmptyMessage(UPDATE_TEXTVIEW);
            sleep(5000);
        }
    });
    t.start();
}

But the correct way to do it is to have the service notify your Activity when to query the database. Not good to query the database every few seconds when it doesn't need to.

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