I have two activities, one is main and I have another activity called Test as well
in the main activity i have a button when I click on this button I go to the Test activity
in the Test activity I want the application to automatically append some text to the textview that it has every 10 seconds
this text can be for example “test”
so every 10 seconds “test” will be added
but, when I leave the activity and go to the main activity, this process will continue happening
so if for example I spend 20 seconds on the main activity and then return to the Test activity, I will see two more “test” strings in the textview..
I tried doing this with timertask and had no success at all
this is the Test activity’s code, in the main activity I just have the button that shows me the other activity
public class test2 extends Activity {
/** Called when the activity is first created. */
private TimerTask task;
private Handler handler;
private TextView tv;
private Timer t;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text1);
t = new Timer();
task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
TextView tv = (TextView) findViewById(R.id.tv1);
tv.append("test");
}
});
}
};
t.schedule(task, 2000);
}
}
when I click in the button of the main activity in order to go to the Test activity I get the following error:
FATAL EXCEPTION: Timer-0
java.lang.NullPointerException
thanks in advance
If you want to implement a way of updating the view from the background, I would recommend switching to use a Service instead, with a timer possibly periodically sending Broadcasts, which the main activity can access with a BroadcastReceiver. The TimerTask could be implemented on the start of the background service.
If you want to immediately update the test class when it loads, you could implement an “update”
BroadcastReceiveron the service as well, whose function would be to send another broadcast with the updated value.This way, you wouldn’t need to worry about your Test activity getting paused while you switch between activities (if that is what you’re going for).
EDIT :
Here is a pretty good tutorial that should have everything you need:
http://www.vogella.de/articles/AndroidServices/article.html