0

how to add a timer to an activity and carry forward its values to the next activity?

I have a timer in my ShuffleButtons.class but when i move on to the next activity ShuffleButtons1.class, the timer value starts from zero. Can somebody tell me how to pass on the timer value to the next activity?

Below is my code :

import java.util.ArrayList;
import java.util.Collections;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShuffleButtons extends Activity {

int id = 1;
static Toast button_press;
int a = 0;
private TextView timerValue;

private long startTime = 0L;

private Handler customHandler = new Handler();

long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;


@SuppressLint("ShowToast")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView( R.layout.shuffle );

    timerValue = (TextView) findViewById(R.id.timerValue);

    button_press= Toast.makeText(this, "1 Presssed", Toast.LENGTH_SHORT);


  //create another two linear layouts which will host 5 buttons horizontally
    LinearLayout top_compte = (LinearLayout)findViewById(R.id.top_compte);
    LinearLayout bottom_calculator = (LinearLayout)findViewById(R.id.bottom_calculator);

    // Create an ArrayList to hold the Button objects that we will create    
    ArrayList<Button> buttonList = new ArrayList<Button>();

    // Create the Buttons, set their text as numeral value of the index variable    
    for (int i = 0; i < 4; i++) {
        final Button b = new Button(this);
        b.setText("" + (i+1));
        b.setGravity(Gravity.CENTER_HORIZONTAL);


        b.setId(i+1);                    // Set an id to Button

        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dealWithButtonClick(b);
            }

            public void dealWithButtonClick(Button b) {
                 switch(b.getId()) {
                  case 1: 
                      if (a==0) {
                          startTime = SystemClock.uptimeMillis();
                            customHandler.postDelayed(updateTimerThread, 0);
                              a=1;
                      }
                      button_press.setText("1 Pressed");
                        button_press.show();

                    break;
                case 2:
                    if (a==1) {
                          a=2;
                         button_press.setText("2 Pressed");
                            button_press.show();
                  }else {
                      button_press.setText("You Pressed the wrong button");
                        button_press.show();

                  }

                    break;
                case 3:
                    if (a==2) {
                          a=3;
                         button_press.setText("3 Pressed");
                            button_press.show();
                  }else {
                      button_press.setText("You Pressed the wrong button");
                        button_press.show();

                  }

                     break;
                case 4: 
                    if (a==3) {
                        timeSwapBuff += timeInMilliseconds;
                        customHandler.removeCallbacks(updateTimerThread);
                          a=4;
                         button_press.setText("Good Going");
                            button_press.show();

// here i move on from ShuffleButtons.class to ShuffleButtons1.class


                Intent intent = new Intent(getApplicationContext(),ShuffleButtons1.class);
                        startActivity(intent);
                        finish();
                  }else {
                      button_press.setText("You Pressed the wrong button");
                        button_press.show();

                  }

                    break;

                      }

            }            
        });
        buttonList.add(b);
    }

    // Shuffle    
    Collections.shuffle(buttonList);


    for (int i = 0; i < 4; i++) {

        // Add the first five Buttons to top_compte
        // Add the last five Buttons to bottom_calculator
        if (i < 2) {
            top_compte.addView(buttonList.get(i));
        } else {
            bottom_calculator.addView(buttonList.get(i));
        }
    }
}   

 // Generates and returns a valid id that's not in use
public int generateUniqueId(){  
    View v = findViewById(id);  
    while (v != null){  
        v = findViewById(++id);  
    }  
    return id++;  
}

private Runnable updateTimerThread = new Runnable() {

    public void run() {

        timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

        updatedTime = timeSwapBuff + timeInMilliseconds;

        int secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 1000);
        timerValue.setText("" + mins + ":"
                + String.format("%02d", secs) + ":"
                + String.format("%03d", milliseconds));
        customHandler.postDelayed(this, 0);
    }

};

}
amit
  • 709
  • 6
  • 17

1 Answers1

0

Don't pass your Timer.

Start your timer in a separate Service, which means to let it run in background.

Make the timer globally accessible using Singleton pattern or custom Application class.

And then access it whenever and wherever you need it.

That's the cleverer way to do it. See this if you are not familiar with the Android Service component.

viz
  • 1,247
  • 16
  • 27
  • could you please give some links to refer, or an idea of a sample code to get an idea.. basically what i need is a timer to start in Activity One and stop in another activity. – amit May 27 '17 at 07:04
  • @amit I already gave you the link to the android training guide. The tutorial with example code is already there. https://developer.android.com/training/run-background-service/create-service.html Write your timer code in your service, put your time variable as a member variable of your service. Start it in your first activity, and in your second, get your service reference, stop the timer, and retrieve your elapsed time. Refer to this on getting the service reference. https://stackoverflow.com/questions/10482171/how-to-get-reference-to-running-service – viz May 28 '17 at 20:14