Reputation: 39
what i have is an image view and i have three pictures and i want the image to be changed automatically every 3 seconds , and i have used timer task to do this and here is my code:
public class MainActivity extends Activity {
private ImageView frame;
private int[] images = {R.drawable.boz_43, R.drawable.boz_42, R.drawable.boz_44};
Timer timer;
int i=0;
private TimerTask updateTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frame = (ImageView)findViewById(R.id.imageView1);
timer = new Timer("TweetCollectorTimer");
timer.schedule(updateTask, 6000L, 3000L);
updateTask = new TimerTask() {
@Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() { // TODO Auto-generated method stub
frame.setImageResource(images[i]);
i++;
if (i > 3)
{
i = 0;
}//if
}//run
});//runnable
}
};//timer task
}
}
but each time i run my code i face a crash and it gives me a fatal exception : it says :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidanim/com.example.androidanim.MainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at java.util.Timer.scheduleImpl(Timer.java:570)
at java.util.Timer.schedule(Timer.java:481)
at com.example.androidanim.MainActivity.onCreate(MainActivity.java:26)
and 26 line is :
timer.schedule(updateTask, 6000L, 3000L);
can you help me please???
Upvotes: 0
Views: 3542
Reputation: 14408
Your updateTask
is null.So use timer.schedule(updateTask, 6000L, 3000L);
after initiating updateTask
So use onCreate
as
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frame = (ImageView)findViewById(R.id.imageView1);
timer = new Timer("TweetCollectorTimer");
updateTask = new TimerTask() {
@Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() { // TODO Auto-generated method stub
frame.setImageResource(images[i]);
i++;
if (i > 3)
{
i = 0;
}//if
}//run
});//runnable
}
};//timer task
timer.schedule(updateTask, 6000L, 3000L);
}
Upvotes: 0
Reputation: 6862
You are using updateTask before creating it. Just call
timer.schedule(updateTask, 6000L, 3000L);
after
updateTask = new TimerTask() { ..
Upvotes: 2