moe
moe

Reputation: 247

Android timer with do while

My code is crashing and I need some help. Everything is running fine except for this part.

There is no errors but it crashes at timer.schedule(loadImg2, 5000); that is before the if (!c.moveToNext())

My question: am I using the timer correctly in the loop? Because that is where the code crashes.
I never see this log "+-+-+-+-+-+-+-+-+- Getting out " or anything that comes after.

do
{
    Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Ttrying to cancel ");
    //timer.cancel();
    Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Timer canceled ");

    timer = new Timer();

    Log.v("log_tag", "+-+-+-+-+-+-+-+-+- New timer created ");
    //delay  amount of time(5s here) in milliseconds before first execution.
    //period  amount of time(1s here) in milliseconds between subsequent executions.

    timer.schedule(loadImg2, 5000); //this did not produce any effect so far

    if (!c.moveToNext())
    {
        //destroy
        timer.cancel();
        myImageView.setImageBitmap(null);
        Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Getting out ");
        //get out of the loop or set c.moveToFirst()
        break;
    }
} while (true);

TimerTask loadImg2 = new TimerTask()
{
    @Override
    //Load Img2
    public void run()
    {
        runOnUiThread(new Runnable()
        {
            public void run()
            {
                Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Inside loadImg2 ");
                titleText.setText(DisplayTitle(c));
                Bitmap bitmap2 = BitmapFactory.decodeFile(c.getString(5));
                myImageView = (ImageView) findViewById(R.id.imageview1);
                myImageView.setImageBitmap(null);
                timer.cancel();
            }
        });
    }
}

Upvotes: 0

Views: 1912

Answers (1)

Vera
Vera

Reputation: 11

There is a problem that you can't set timer.schedule() more than once time. Try to catch an exception:

try{
  timer.schedule(loadImg2, 5000);
} catch (IllegalArgumentException e){
  Log.v(TAG, "IllegalArgumentException");
} catch (IllegalStateException e){
  Log.v(TAG, "IllegalStateException");
}

Then the application doesn't crash. But the timer will set just in the first time.

I don't know the solution of this problem. I am trying to find it too.

Upvotes: 1

Related Questions