skip to Main Content

I am developing a step counter app in Android Studio in Java, the counters are all working fine, I have added a button which would reset all the counters to 0, but when I click the reset button the counters are set to 0 but when I change the page or move the phone the value returns the same as before.



import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;



public class MainActivity extends AppCompatActivity implements SensorEventListener {

    FirebaseAuth auth;
    TextView textViewSteps, textViewCalories, textViewMiles;
    FirebaseUser user;
    SensorManager sensorManager;
    FirebaseFirestore db;
    Button resetBtn;





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

        auth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();

        textViewSteps = findViewById(R.id.step_counter);
        textViewCalories = findViewById(R.id.calories);
        textViewMiles = findViewById(R.id.miles);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        resetBtn = findViewById(R.id.resetBtn);

        user = auth.getCurrentUser();
        if (user == null) {
            Intent intent = new Intent(getApplicationContext(), Login.class);
            startActivity(intent);
            finish();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.BODY_SENSORS) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.BODY_SENSORS, Manifest.permission.ACTIVITY_RECOGNITION, Manifest.permission.READ_CALENDAR}, 1);
            }
        }

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);

        bottomNavigationView.setSelectedItemId(R.id.home);

        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.home:
                        return true;
                    case R.id.health:
                        startActivity(new Intent(getApplicationContext()
                                , Health.class));
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.rewards:
                        startActivity(new Intent(getApplicationContext()
                                , Reward.class));
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.profile:
                        startActivity(new Intent(getApplicationContext()
                                , Profile.class));
                        overridePendingTransition(0, 0);
                        return true;

                }
                return false;
            }
        });

        resetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
            }
        });

        
        DocumentReference countersDocRef = db.collection("CounterDetails").document(user.getUid());
        countersDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if (documentSnapshot.exists()) {
                    int savedSteps = documentSnapshot.getLong("steps").intValue();
                    double savedCalories = documentSnapshot.getDouble("calories");
                    double savedMiles = documentSnapshot.getDouble("miles");
                    textViewSteps.setText(String.valueOf(savedSteps));
                    textViewCalories.setText(String.format("%.2f Kcal", savedCalories));
                    textViewMiles.setText(String.format("%.2f Miles", savedMiles));
                } else {
                  
                    reset();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getApplicationContext(), "Error retrieving saved data: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }









    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permissions granted!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Permissions denied!", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
            int newSteps = (int) event.values[0];
            double calories = newSteps * 0.04;
            double miles = newSteps * 0.0005;
            textViewSteps.setText(String.valueOf(newSteps));
            textViewCalories.setText(String.format("%.2f Kcal", calories));
            textViewMiles.setText(String.format("%.2f Miles", miles));

            db = FirebaseFirestore.getInstance();
            DocumentReference countersDocRef = db.collection("CounterDetails").document(user.getUid());

            Map<String, Object> data = new HashMap<>();
            data.put("steps", newSteps);
            data.put("calories", calories);
            data.put("miles", miles);

            countersDocRef.set(data)
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getApplicationContext(), "Error Saving Data: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }





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

    @Override
    protected void onResume() {
        super.onResume();
        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (countSensor != null) {
            sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
        } else {
            Toast.makeText(this, "Sensor not found", Toast.LENGTH_SHORT).show();
        }
        db = FirebaseFirestore.getInstance();
        user = FirebaseAuth.getInstance().getCurrentUser();
    }





    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    public void reset() {
        db.collection("CounterDetails").document(user.getUid())
                .update("steps", 0, "calories", 0, "miles", 0)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(getApplicationContext(), "Counter reset successful", Toast.LENGTH_SHORT).show();
                        
                        textViewSteps.setText("0");
                        textViewCalories.setText("0 Kcal");
                        textViewMiles.setText("0 Miles");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(), "Error resetting counter: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }



}

2

Answers


  1. Chosen as BEST ANSWER

    Changed sensor to Step Detector now it works fine.


  2. when you change the page you are triggering the "onResume()" followed by "onSensorChanged" and this last will write the new data in the DB, you can try commenting "onResume()" and see if the values has changed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search