views:

42

answers:

1

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!

+1  A: 

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.

BrennaSoft
Thank you very much. Exactly what I wanted. I added t.stop(); to onPause() and t.start() to onResume(). Is this enough to make sure that thread is not running while activity is not in focus?
Levara
That is how you could do it but you really shouldn't do it that way, and you cannot restart threads. Read this other question from today that is a better solution to solve your problem.http://stackoverflow.com/questions/3095207/how-to-restart-a-thread-in-android
BrennaSoft
Thanks again. You're right, this really is a bad solution... :P I'm going to try with an Intent... binding is still a little out of my league.
Levara