1

I have developed an app that has two buttons (left and right) and a Textview that will pop up on the screen.Each button has it's corresponding word.
The user has to click the button that corresponds to TextView's word as quickly as possible when it shows. I want to calculate it's reaction time on clicking the button.

Below is my code.

public class Place_to_go_1 extends AppCompatActivity {

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

        placeone = Global_variables.getFirst_choice_label();
        placetwo = Global_variables.getSecond_choice_label();
        p_one = (TextView)findViewById(R.id.p_one);
        p_two = (TextView)findViewById(R.id.p_two);

        btnleft = (ImageButton)findViewById(R.id.btnleft);
        btnright = (ImageButton)findViewById(R.id.btnright);

        next = (ImageButton)findViewById(R.id.Next);
        lblmaintext = (TextView)findViewById(R.id.lblmaintext);
        lblprompt = (TextView)findViewById(R.id.lblprompt);
        lblreact = (TextView)findViewById(R.id.lblreact);
        imgmain = (ImageView)findViewById(R.id.imgmain);
        //prac = (ImageView) findViewById(R.id.prac);

        Intent intent = getIntent();
        final String randomId = intent.getStringExtra("Info_id");

        //============ validate image if not empty
        setImage_onLaunch();

        //==== populate left and right choices===
        populate_headers(placeone, placetwo);
        //==== populate attributes=====
        populate_attributes();

        //============== instruction ======
        setInstruction();

        //=============media
        wrong_press = MediaPlayer.create(this, R.raw.wrong_press);
        react_fast = MediaPlayer.create(this, R.raw.react_faster);

        //=== left button click trigger
        btnleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String position = "H";
                    if (tanan[counter].equals(p_one.getText().toString())) {

                        lblprompt.setVisibility(View.INVISIBLE);

                        HashMap<String,String> queryValues = new HashMap<String, String>();
                        queryValues.put("Info_id",randomId);
                        queryValues.put("Choice",p_one.getText().toString());
                        queryValues.put("Reaction_time",String.valueOf(elapsedTime));
                        queryValues.put("Position",position);
                        queryValues.put("Main",main);
                        queryValues.put("Error",error);
                        mydb.insertTest(queryValues);


                        counter++;
                        if (counter < tanan.length) {
                            btnleft.setEnabled(false);
                            btnright.setEnabled(false);
                            timeStamp = System.currentTimeMillis();
                            //Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
                            getreactionTime(p_one.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
                            setIntervalTime();

                        } else {
                            //======end sa data

                            postEnd();
                        }
                    } else {
                        // Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
                        //wrong_press.start();
                        wrong_click_audio();
                        error = "1";
                        lblprompt.setVisibility(View.VISIBLE);
                    }


            }
        });
        //==== right button click trigger
        btnright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String position = "A";

                    if (tanan[counter].equals(p_two.getText().toString())) {

                        lblprompt.setVisibility(View.INVISIBLE);



                        HashMap<String,String> queryValues = new HashMap<String, String>();
                        queryValues.put("Info_id",randomId);
                        queryValues.put("Choice",p_two.getText().toString());
                        queryValues.put("Reaction_time", String.valueOf(elapsedTime));
                        queryValues.put("Position",position);
                        queryValues.put("Main",main);
                        queryValues.put("Error",error);
                        mydb.insertTest(queryValues);



                        counter++;
                        if (counter < tanan.length) {
                            btnleft.setEnabled(false);
                            btnright.setEnabled(false);
                            timeStamp = System.currentTimeMillis();
                            //Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
                            getreactionTime(p_two.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
                            setIntervalTime();
                        } else {


                            //======end sa data
                            postEnd();
                        }
                    } else {
                        // Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
                        // wrong_press.start();
                        wrong_click_audio();
                        error = "1";

                        lblprompt.setVisibility(View.VISIBLE);
                    }
                }



        });


        // ==== next button for the next activity (Place to go 2)
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = getIntent();
                String randomId = intent.getStringExtra("Info_id");


                //============= launch activity 2 for place to go
                    if (instruct == true) {
                        next.setVisibility(View.INVISIBLE);
                        // prac.setVisibility(View.VISIBLE);
                        CountDownTimer();

                            } else {
                                //Toast.makeText(getApplication(),"Saved Successfully.",Toast.LENGTH_SHORT).show();
                                Intent i = new Intent(getApplicationContext(), Place_to_go_2.class);
                                i.putExtra("Info_id", randomId);
                                startActivity(i);


                    }

            }
        });


    }



public void interval(){
        if(counter < tanan.length){
        lblmaintext.setVisibility(View.VISIBLE);
        timeRun = System.currentTimeMillis();
        btnleft.setEnabled(true);
        btnright.setEnabled(true);
        lblmaintext.setText(tanan[counter]);
        setImage();
        imgmain.setVisibility(View.VISIBLE);

        react = true;
        reacFaster();
        }else{
        //======end sa data
        Toast.makeText(Place_to_go_1.this, "End data", Toast.LENGTH_SHORT).show();
        lblmaintext.setVisibility(View.VISIBLE);
        lblmaintext.setText("Ok for now");
        }


        }

public void setIntervalTime(){
        react = false;
        lblreact.setVisibility(View.INVISIBLE);
        reactFaster_timer.cancel();
        lblmaintext.setVisibility(View.INVISIBLE);
        lblreact.setVisibility(View.INVISIBLE);
        imgmain.setVisibility(View.INVISIBLE);

        timer = new CountDownTimer(Global_variables.interval_time_before_choices_will_show,Global_variables.interval_time_before_choices_will_show) {
@Override
public void onTick(long millisUntilFinished) {

        }

@Override
public void onFinish() {
        interval();
        }
        }.start();
        }
        int counter_countdown = 0;
        int drawwable_amber = R.drawable.amber;
        String arr[] = {"Ready...","Set...","Start."};
public void CountDownTimer(){

        btnleft.setVisibility(View.INVISIBLE);
        btnright.setVisibility(View.INVISIBLE);
        lblmaintext.setBackgroundResource(0);

        timer = new CountDownTimer(4000,1000) {
@Override
public void onTick(long millisUntilFinished) {
        lblmaintext.setTextSize(35);

        lblmaintext.setText(arr[counter_countdown]);
        counter_countdown++;
        }

@Override
public void onFinish() {
        btnleft.setVisibility(View.VISIBLE);
        btnright.setVisibility(View.VISIBLE);
        lblmaintext.setBackgroundResource(drawwable_amber);
        // lblmaintext.setText(tanan[counter]);
        //setImage();
        val_first_launch();
        timeRun = System.currentTimeMillis();

        react = true;
        reacFaster();

        }
        }.start();
        }


public void reacFaster(){
        reactFaster_timer = new CountDownTimer(Global_variables.reaction_time_first_param,Global_variables.reaction_time_second_param) {
@Override
public void onTick(long millisUntilFinished) {

        }

@Override
public void onFinish() {
        if(react == true){
        //Toast.makeText(Place_to_go_1.this, "please react faster", Toast.LENGTH_SHORT).show();
        react_fast.start();
        lblreact.setVisibility(View.VISIBLE);
        }
        }
        }.start();
        }



public void populate_headers(String one,String two){
        //== this methos sets headers as random==//
        headers = new ArrayList<String>();
        headers.add(one);
        headers.add(two);
        Collections.shuffle(headers);
        p_one.setText(headers.get(0));
        p_two.setText(headers.get(1));
        }
public void populate_attributes(){
        attributes = new ArrayList<String>();
        for(int h =0;h < 5;h++){
        attributes.add(placeone);
        attributes.add(placetwo);
        }
        Collections.shuffle(attributes);
        tanan = new String[attributes.size()];
        for(int k = 0; k < tanan.length;k++ ){
        tanan[k] = attributes.get(k);
        }
        }

public void postEnd(){
        instruct = false;
        lblprompt.setVisibility(View.INVISIBLE);
        btnright.setVisibility(View.INVISIBLE);
        btnleft.setVisibility(View.INVISIBLE);
        next.setVisibility(View.VISIBLE);
        lblmaintext.setBackgroundResource(0);
        lblmaintext.setTextSize(20);
        p_one.setVisibility(View.INVISIBLE);
        p_two.setVisibility(View.INVISIBLE);

        imgmain.setVisibility(View.INVISIBLE);

        reactFaster_timer.cancel();
        lblreact.setVisibility(View.INVISIBLE);
        lblmaintext.setText("Well done!\nNext, is the main task. It is exactly the same as before but this time words will appear on the screen that might distract you. \nPlease respond as quickly as you can.\n Press Next to begin");
        }



//=========== validate if image is enabled/ disble if not set
public void setImage_onLaunch(){
        if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
        disbaleImage();
        }else{

        }
        }

    public void setImage(){
      /*  if(tanan[counter].equals(p_one.getText().toString())){
            imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
        }else{
            imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
        }*/
        if(placeone.equals(tanan[counter])){
            imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
        }else{
            imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
        }
    }


    public void val_first_launch(){
        if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
            lblmaintext.setVisibility(View.VISIBLE);
            lblmaintext.setText(tanan[counter]);
        }else{
            imgmain.setVisibility(View.VISIBLE);
            if(placeone.equals(tanan[counter])){
                imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
            }else{
                imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
            }
        }
    }


    public void disbaleImage(){
        imgmain.setBackgroundResource(0);
        imgmain.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        startActivity(new Intent(getApplication(), MainActivity.class));
        finish();

    }


    public String getreactionTime(String domain, String time){
      //  Toast.makeText(Place_to_go_1.this, time, Toast.LENGTH_SHORT).show();
        //== get reaction time to every activity
        Global_variables.set_timeStamps(domain, time);
        return domain;
    }


    //===== prompt instruction====
    public void setInstruction(){
        btnleft.setVisibility(View.INVISIBLE);
        btnright.setVisibility(View.INVISIBLE);
        lblmaintext.setBackgroundResource(0);
        lblmaintext.setTextSize(20);
        lblmaintext.setText("Instruction:\n\nIf " + p_one.getText().toString() + " appears, press arrow left.\n If " + p_two.getText().toString() +
                " appears, press arrow right.\n\nRespond as quickly as you can.");
        next.setVisibility(View.VISIBLE);
    }
    //===== prompt instruction====


    public void wrong_click_audio(){

        wrong_press.start();


    }

    //=============end class====================

    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
           // Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            //Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
}
Gautam Savaliya
  • 1,403
  • 2
  • 20
  • 31
Crissy
  • 263
  • 1
  • 2
  • 4

3 Answers3

2

Here a simple logic to calculate reaction time is to create a variable which hold a time when a question is popped up to user and the time when a user show a click reaction to question and calculate the time difference between these two action.

long timeWhenQuestionShowed = System.currentTimeMillis();
long timeWhenUserReacted = System.currentTimeMillis();
long reactionTime = timeWhenQuestionShowed - timeWhenUserReacted;
ujjwal mainali
  • 379
  • 1
  • 5
  • 17
  • Answer of this will not satisfy the desired condition since you are executing both lines sequentially without any click-checks on button. – Talha Sep 30 '16 at 05:55
  • 1
    Its a logic i presented now its upto you to find out when the events occurs and calculate the time difference.Here in stackflow i don't think just giving up all the code specific to a certain situation is effective way to learn – ujjwal mainali Sep 30 '16 at 05:58
  • Thats exactly the question, isn't it? – Talha Sep 30 '16 at 05:58
  • i don't think i need to post a code on how to listen a click event in a view. – ujjwal mainali Sep 30 '16 at 06:03
1

The idea is to calculate the difference between 2 points in time. I will write 2 examples of calculating time difference in Java / measuring reaction time in Java:

  1. System.nanoTime() or System.currentTimeMillis()

Differences are discussed here: Time measuring overhead in Java

long endTimeNanoSec = 0;
long startTimeNanoSec = System.nanoTime();
myWorkThatNeedsTiming(); // wait for user button press here
endTimeNanoSec = System.nanoTime();

long totalWorkTimeNanos = endTimeNanoSec - startTimeNanoSec;
  1. Java StopWatch

JavaDoc: StopWatch

Stopwatch stopwatch = Stopwatch.createStarted();
myWorkThatNeedsTiming(); // wait for user button press here
stopwatch.stop();

long totalWorkTimeMillis = stopwatch.elapsedMillis();
Community
  • 1
  • 1
Tadija Bagarić
  • 2,495
  • 2
  • 31
  • 48
1

This should help:

Try using onTouch instead of onClick.

long timeBefor=0;
long timeReaction=0;

btnleft.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {

case MotionEvent.ACTION_DOWN:  // when pressed
    timeBefore=System.currentTimeMillis();
    break;
case MotionEvent.ACTION_UP:  // when released
    timeReaction=System.currentTimeMillis() - timeBefore; // calculate difference
    break;

}

}

timeReaction is your desired value.

Talha
  • 903
  • 8
  • 31