0

I want to move to another Activity after 5 seconds. (Step4Activity -> WeightActivity)

I found this code, and it worked.

 new Handler().postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            Intent intent = new Intent(Step4Activity.this, WeightActivity.class);
            startActivity(intent);
        }
    }, 5000); 

But I want to use a variable 'count' as a parameter 'delaymillis' like this, but it didn't work.

 new Handler().postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            Intent intent = new Intent(Step4Activity.this, WeightActivity.class);
            startActivity(intent);
        }
    }, count * 1000);  // int count = 5

Is there any way to use variable?

Here's my full code. (Step4Activity.java)

package com.example.starbucksook;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;

public class Step4Activity extends AppCompatActivity {

    //TextView countdown_text;

    //LinearLayout timeCountSettingLV, timeCountLV;
    //TextView hourET, minuteET, secondET;
    //TextView hourTV, minuteTV, secondTV, finishTV;
    //Button startBtn;
    //int hour, minute, second;
    int count = 5;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_step4);

        // Unrelated code skipped


        /*Here is 'Handler-postDelayed' method.*/
        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                Intent intent = new Intent(Step4Activity.this, WeightActivity.class);
                startActivity(intent);
            }
        }, count * 1000); 

}

Hunter
  • 19
  • 7
  • these lines are so simple that there is no room for bug... yes, you can use variable obviusly, it must work. have you builded properly changed version and tried it on device/emulator? maybe stripped out code may have some impact on that (e.g. changes`count` flag) – snachmsm Dec 02 '21 at 15:07
  • btw. are you familiar with fact that leaving pending `Runnable` for some freely created `new Handler()` is in fact memory leak possibility? – snachmsm Dec 02 '21 at 15:07
  • @snachmsm I used to execute it on emulator. I tried it on device and it worked ... Don't know the reason but it worked. Thanks for your comment! – Hunter Dec 02 '21 at 15:22

0 Answers0