Create a Simple Pedometer and Step Counter in Android

Pedometer

Anu S Pillai

The Admin at GadgetSaint.com

You may also like...

109 Responses

  1. Royal Lachinov says:

    This code is not working. There is lack og textview.setText()

  2. Royal Lachinov says:

    Should we declare permission in the Manifest file for run this app

  3. Anu S Pillai says:

    No permissions required

  4. Anu S Pillai says:

    Can you tell where do we need textview.settext?

  5. Anonymous says:

    I implemented it in my app and it works perfectly! Thanks so much!

  6. john says:

    why i cant insert data in my sql lite ? my app crash

  7. Anu S Pillai says:

    What error are you getting? Share your logcat

  8. jeffrey says:

    I don’t understand SensorFilter.java why are you used them?

  9. Anu S Pillai says:

    As the name says, its used for filtering out unwanted values from accelerometer data

  10. France says:

    Is it possible to make public step listener data to string?

  11. Anu S Pillai says:

    Yes. You make cast the value to String.

  12. rahul ahuja says:

    the app is not working … there is no error but the app is crashing .. what to do next ?????

  13. Anu S Pillai says:

    Can you post the logcat?

  14. rahul ahuja says:

    now error is coming cannot resolve symbol tvsteps???

  15. Anu S Pillai says:

    Tvsteps is the textview which you need to link with your layout xml using findviewbyid

  16. rahul ahuja says:

    when im declaring it with textview then it is coming tvsteps is not used

  17. Anu S Pillai says:

    I think I need to see your code.

  18. Zain says:

    can’t the apps stored the walked data before on Firebase ?

  19. Anu S Pillai says:

    I can’t get you. Do you mean you want to write step count data in Firebase? If that is the case you can do it. https://firebase.google.com/docs/database/android/read-and-write

  20. Zain says:

    Yes, write the step count data on Firebase. How I can do this ? I mean the step are saved in Firebase

  21. Joe says:

    Hi! Can i convert lister.step as model class ?

  22. alex says:

    Hello just a question, thanks for the code i tried it but can you explain me a little how it’s works ?
    Also this code is not very sensitive how can i increase sensibility ? Did I have to increase or decrease the treeshold ?

  23. Anu S Pillai says:

    Decrease the threshold to increase the sensitivity.

  24. alex says:

    I will try thank you, also this code works, can you explain me the principe? It’s a part of my thesis , i can quote you if you want 🙂 .

  25. Anonymous says:

    Hi, step(long timeNs) method not calling in MainActivivty. Any solution for this.

  26. Anonymous says:

    Yo man,
    thanks 4 the example, it works!

  27. kingslanding1 says:

    STEP_THRESHOLD and STEP_DELAY_NS are not appropriate for step detect. Step increases when hang the phone up and down.

  28. Vishnu says:

    Great work. How do you calculate distance from these steps?

  29. shanks says:

    I implemented its working . Thank you so much.

  30. Tanvi Sharma says:

    Hello Sir, Thanks for posting this code.
    but i’m having an error in my code in Tvstep statement (at the last of main activity)
    plz help!

  31. Anu S Pillai says:

    What error are you getting?

  32. Tanvi Sharma says:

    in error its saying Tvsteps can not be resolved.

    plz can i get ur emailid? ill send u screenshots, then u can check in that.

  33. Tanvi Sharma says:

    there is no other error except this

  34. Anu S Pillai says:

    You are getting this error because TvSteps is a TextView which need to be initialised in your onCreate using “findviewbyid”. You need to link your TvSteps TextView with the XML layout.

  35. Anu S Pillai says:

    Do something like this in your activity onCreate:

    TextView TvSteps = (TextView) findviewbyid(R.id.yourtextviewidinxml); // replace with your TextView id defined in layout XML

  36. Tanvi Sharma says:

    //please check the code
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;

    public class Two extends ActionBarActivity implements StepListener,SensorEventListener {

    private TextView textView;
    private StepDetector simpleStepDetector;
    private SensorManager sensorManager;
    private Sensor accel;
    private static final String TEXT_NUM_STEPS = “Number of Steps: “;
    private int numSteps;

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);

    // Get an instance of the SensorManager
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    simpleStepDetector = new StepDetector();
    simpleStepDetector.registerListener(this);

    //Tvsteps is initialised here
    TextView TvSteps = (TextView) findViewById(R.id.tv_steps);
    Button BtnStart = (Button) findViewById(R.id.btwo1);
    Button BtnStop = (Button) findViewById(R.id.btwo2);

    BtnStart.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

    numSteps = 0;
    sensorManager.registerListener(Two.this, accel, SensorManager.SENSOR_DELAY_FASTEST);

    }
    });

    BtnStop.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

    sensorManager.unregisterListener(Two.this);

    }
    });

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    simpleStepDetector.updateAccel(
    event.timestamp, event.values[0], event.values[1], event.values[2]);
    }
    }

    @Override
    public void step(long timeNs) {
    numSteps++;

    //error in this Tvsteps
    TvSteps.setText(TEXT_NUM_STEPS + numSteps);

    }

    }

    //there r no errors in xml layput

  37. Tanvi Sharma says:

    //i have taken the same name in my xml layout, see:

  38. Tanvi Sharma says:
  39. Anu S Pillai says:

    Make your TextView TvSteps global variable, declare it outside onCreate

    TextView TvSteps;

    OnCreate{

    TvSteps = (TextView) findViewById(R.id.tv_steps);

    }

  40. Tanvi Sharma says:

    By this that error is removed in TvSteps … Thanks!
    but a new problem has occured,
    its saying:

    Sytax error on token “OnCreate”, delete this token.

  41. Anu S Pillai says:

    Share your entire code again

  42. Anu S Pillai says:

    I think you copy pasted the code I send you……Keep your onCreate the way it is…..just make your TextView global…..the code I send is just an example for your understanding

  43. Tanvi Sharma says:

    WoW!! thankyou so muchh … no errors now finally 🙂

    Bdw why was it showing error when i declared it inside OnCreate?
    this is a right way, then wht was the need to declare it as global?? we didnt declare button as global but its still working.. then what was the problem?

  44. Anu S Pillai says:

    When you declare inside onCreate it’s a local variable to onCreate and it’s scope is limited to onCreate. Declaring global you can access it from anywhere in the class. Here you are trying to access the local variable of onCreate outside….that’s why it’s showing error. By the way you need to work on your basics.

  45. Tanvi Sharma says:

    Sir,one more problem … there r no errors in the code now.
    but the application is not working on d phone. i mean, its opening up, but the buttons r not working, no steps r being counted, though the code is complete n corrct

  46. Tanvi Sharma says:

    n yes sir, ill revise the basics, but right now plz help

  47. Charlie Simmons says:

    Is it possible for the app to still count steps even when the phone is locked?

  48. ali says:

    Hy Anu! Why did not you used Step_count_sensor and step_detect_sensor? What is the best practice using those sensors or using own logic?

  49. Anu S Pillai says:

    Most of the Android devices doesn’t have an inbuilt Step Counter Sensor. In that case use my code. My code works on accelerometer.

  50. Hey man,
    I would love if you commented your code and possibly tossed it on github 🙂

  51. Christian says:

    This is not working for me 🙁

  52. Risca says:

    Do you have any references from where you got the formulas in SensorFilter class? Would you give me some information please..

  53. Pankaj says:

    This code is very helpful for me.
    sir in future , can i ask any question regarding to this code and about pedoMeter

  54. Pankaj says:

    In this code ,do you have any permission required in manifest

  55. Jean says:

    Well, what is the inside algorithm?
    How do you figure out this from scratch?

  56. Henry says:

    Awesome! Would you mind putting the codes on github?

  57. Anu S Pillai says:

    Definitely I will take out some time to put it on GitHub with a sample project as I am getting lot of queries about this article.

  58. Risca says:

    Do you have any references from where you got the formulas in SensorFilter class? Would you give me some information please

  59. Rishav says:

    pedometer not working while walking….but working on shake up device. When i put my device in pocket by click start button then move steps..after steps,the number of steps remain same..not working

    STEP_THRESHOLD and STEP_DELAY_NS are not appropriate for step detect. Step increases when hang the phone up and down.

  60. Danny Forrest says:

    Are there no import statement? I cannot get this to compile at all. The errors are mainly that the compiler cannot find things.

  61. Harsh says:

    what is the algorithm here? only sensor filter?

  62. Dwiki says:

    Do you have any references from where you got the formulas in SensorFilter class? Would you give me some information please

  63. Dwiki says:

    this is formulas ERSP Energy-efficiet Real Time Smartphone Pedometer ?

  64. Raghuram says:

    I am unable to understand and compile with the above example. Someone help me out either in concepts of how to create or provide me the complete working code

  65. Raghuram says:

    I am unable to buid with the above example. Someone help me out either in concepts of how to create or provide me the complete working code

  66. some android programmer says:

    Thanks man!

  67. Harry Naeem says:

    I used your code. It counts the steps when motion is detected. But there are some problems in it. I have posted a question regarding it on StackOverflow at https://stackoverflow.com/questions/46823952/pedometer-step-counter-in-android.Can you please address these problems. Thank you

  68. Anonymous says:

    Can the app still running after exit the app ?

  69. shreyash says:

    i have one problem like: Sensor and Listener is Null .
    what is mean of this please help me

  70. neer says:

    Hey can we make service for this . if yes how can please tell me

  71. Anonymous says:

    Thanks for sharing the algorithm.

  72. slowjac says:

    How can I calculate the distance?

  73. behzad says:

    how to maximize the threashold sensitivity?
    50f mean float so we have to make it for ex 500f to make it more sensitive?

  74. zeeshan basharat says:

    Thanks brother this code is working properly little bit errors were occur but in others comments on this post there was a solution for these errors .
    but i need one favor can you please describe ho this code is working i have a project code demo on 4th dec 2017.

  75. I have noticed you don’t monetize your site, don’t waste your traffic, you can earn additional cash every month
    because you’ve got hi quality content. If you want to know how to make extra bucks, search
    for: Boorfe’s tips best adsense alternative

  76. swapnil says:

    Hi, nice post.
    How can I find if someone is climbing steps up or down?

  77. Natalie Koroleva says:

    Rishav and everyone who says that pedometer doesn’t work in pocket!
    I had the same problem and first I thought that the algorythm was wrong.
    I changed the threshold value but that didn’t help.
    And finally I’ve got the solution (though I’m not saying for all devices).
    The point is that Android turns on the save energy mode when you turn off the screen. System saves the resourses being in a sleeping mode and your app stops counting steps.
    Read about the PowerManager WakeLock and the WAKE_LOCK permission, that’s what helped me (it keeps CPU in working state even if the screen is turned off). Just now I’ve tried to count steps with my device (screen off) in a back pocket and it works great even with a standart threshold = 50.
    Thanks for sharing this algorythm, it’s great.

  78. Anonymous says:

    Woah this is cool! thanks alot could you complete this project ? with simple weekly graph?

  79. LastJillian says:

    I have noticed you don’t monetize your website, don’t waste your traffic, you can earn additional bucks every
    month because you’ve got high quality content. If you want to know
    how to make extra money, search for: Mertiso’s tips best adsense alternative

  80. Shankar says:

    When i click the start and stop button nothing happens

  81. Hassan Ali Mughal says:

    I can show the steps count on next page(todays steps) the method is????

  82. Eduardo says:

    Hello and nice code.

    In some phones (Samsung) a message is shown that the app is consuming a lot of battery…

    May be necesary some parameter modification in STEP_DELAY_NS or SENSOR_DELAY_FASTEST or where?

  83. Abbasi says:

    How can we modify this code to work in Fragments ?

  84. Ed says:

    Hi,
    I’ve seen some users ask this question, can you give some reference on the filter algorithm you used ??

  85. oo says:

    Hi!

    How can i keep it from resetting while i’m turning the phone to horizontal view?

  86. Doz3r says:

    Hi, is the final working app tossed into GitHub? Best wishes!

  87. zainab says:

    Great! Thank you it working perfect Anu.
    can we make this step listener auto? i mean is it possible to make it detects the steps and update without the start button?

  88. Vishwal Shah says:

    Hey! this code executes but I tried on the emulator. Can you confirm if it works or doesn’t work on an Emulator?
    Thank you so much!

  89. Mohit yadav says:

    i cant run these codes when i click start button no response in it so pls help me how can i run it

  90. Mohit yadav says:

    there r no errors in the code now.
    but the application is not working on d phone. i mean, its opening up, but the buttons r not working, no steps r being counted

  91. Alok says:

    Should count steps even when app is in background or device is locked.?

  92. Shanaka says:

    Thank you dude… it’s super working..

  93. priya says:

    i need a explanation for the code of step detector and sensor filter

  94. BestMarcus says:

    I see you don’t monetize your website, don’t waste your traffic, you can earn extra cash every month.
    You can use the best adsense alternative for any type of website (they approve
    all websites), for more details simply search in gooogle:
    boorfe’s tips monetize your website

  95. Imran Ansari says:

    Nice implementation, it works for me.
    Thanks

  96. Dean says:

    Thank you very much for this article. I found it helpful, informative, and enjoyable.

  97. Astha says:

    // Will listen to step alerts
    public interface StepListener {

    public void step(long timeNs);

    }
    Error in this java file
    missing method body or declare abstract
    please tell me where i am wrong ?

  98. AVINASH ACHARYA says:

    works fine but the application is not that accurate! i would like you to improvise this application!!
    you can first recognize the activity then calculate the steps!

    for recognizing the activity you can follow this website

    https://www.androidhive.info/2017/12/android-user-activity-recognition-still-walking-running-driving-etc/

  99. AVINASH ACHARYA says:

    Astha did you also deleted the package line? i guess that would be the cause of error

    MY CODE

    package com.example.avinashacharya.step_counter; // I am talking about this line, this might differ from yours
    // Will listen to step alerts
    public interface StepListener {

    public void step(long timeNs);

    }

  100. Astha says:

    package com.example.android.stepscounter;

    /**
    * Created by asthajindal on 03-10-2018.
    */

    public class StepListener {
    public void step(long timeNs);
    }

    this is what exactly in my file
    please help me out as it is really urgent

  101. Astha says:

    Sytax error on token “OnCreate”, delete this token.

    package com.example.android.stepscounter;

    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity implements SensorEventListener, StepListener {
    private TextView textView;
    private StepDetector simpleStepDetector;
    private SensorManager sensorManager;
    private Sensor accel;
    private static final String TEXT_NUM_STEPS = “Number of Steps: “;
    private int numSteps;
    TextView TvSteps;
    TextView BtnStart;
    TextView BtnStop;

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

    // Get an instance of the SensorManager
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    simpleStepDetector = new StepDetector();
    simpleStepDetector.registerListener(this);

    TvSteps = (TextView) findViewById(R.id.tv_steps);
    BtnStart = (Button) findViewById(R.id.btn_start);
    BtnStop = (Button) findViewById(R.id.btn_stop);

    BtnStart.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

    numSteps = 0;
    sensorManager.registerListener(MainActivity.this, accel, SensorManager.SENSOR_DELAY_FASTEST);

    }
    });

    BtnStop.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

    sensorManager.unregisterListener(MainActivity.this);

    }
    });

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    simpleStepDetector.updateAccel(
    event.timestamp, event.values[0], event.values[1], event.values[2]);
    }
    }

    @Override
    public void step(long timeNs) {
    numSteps++;
    TvSteps.setText(TEXT_NUM_STEPS + numSteps);
    }

    }

    please help

  102. Astha says:

    working now thanks a lot

  103. Astha says:

    working now thanks a lot

  104. Parth says:

    This works great, but one issue i am facing is that it is very sensitive. when i pickup my phone from the desk, it counts 4 steps. also when the phone is on the desk and i give a small bang, it count that as a step too. How can i resolve this? i tried to debug it by changing STEP_THRESHOLD =20. still the bang gives velocityEstimate of 21-50 on the variarion of the bang i give. Please help.

  105. Parth says:

    Also can you mention which algorithm you have referred/studied when making this code, so i can get a better understanding of the code.

  106. Parth says:

    Ok the issue is resolved my bad, i had kept the threshold to 10. But now i am facing one more issue is that when i keep the device in my pocket i get approx correct(always less) count. but if i keep the phone in my hand and swing my arm while walking that it does not count. what should i do to improve that.

Leave a Reply

Your email address will not be published.