1

I have created a speedometer application, I want it to display the max speed the user has achieved. How do I find the highest speed the user has achieved?

I have already tried to contain the speeds in an array so that I can find the highest speed using the math.max function but the speeds in a variable keep changing how do I store the past speeds to compare and find the highest speed.

my main3activity:

public class Main3Activity extends AppCompatActivity implements android.location.LocationListener {
int arr[];

public int borat;


  public  float boo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        LocationManager lm =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
        this.onLocationChanged(null);
      final  TextView mTextField=(TextView)this.findViewById(R.id.textView);

        new CountDownTimer(11000, 1000) {

            public void onTick(long millisUntilFinished) {
                mTextField.setText("" + millisUntilFinished / 1000);
            }

            public void onFinish() {
                Intent myIntent = new Intent(Main3Activity.this,
                        aftergame.class);
                startActivity(myIntent);
            }
        }.start();


    }
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
    public boolean checkLocationPermission()
    {
        String permission = "android.permission.ACCESS_FINE_LOCATION";
        int res = this.checkCallingOrSelfPermission(permission);
        return (res == PackageManager.PERMISSION_GRANTED);
    }


    @Override
    public void onLocationChanged(Location location) {
        int cpeeda;
        int cpeedb;
        final int speed;

        TextView txt=(TextView)this.findViewById(R.id.st);
if(location==null){
txt.setText("0 m/s");

}else{
 float  cpeed=location.getSpeed();
 float  cpeed1=location.getSpeed();
    cpeeda=(int)cpeed;


    cpeeda=arr[0];
   borat= Math.max(0,arr[0]);
    txt.setText(cpeeda + " m/s");
}
}
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {   
    }   
}

my activity which displays the high speed:

public class aftergame extends AppCompatActivity {
Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aftergame);
        button = (Button) findViewById(R.id.button2) ;
        Main3Activity m=new Main3Activity();
        TextView   tm=(TextView)this.findViewById(R.id.textView3);
        tm.setText(""+m.borat);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(aftergame.this,
                        MainActivity.class);
                startActivity(myIntent);   
            }
        });
    }
    }
Dhaiyur
  • 498
  • 4
  • 14
codeboy96
  • 11
  • 6

1 Answers1

1

Here:

cpeeda=arr[0];
borat= Math.max(0,arr[0]);

That is non-sensical. I guess you meant to assign

arr[0] = cpeeda;

But even that doesn't make much sense. The idea of arrays is that they provide multiple data points. When you only assign a value into the first slot, all the other array slots stay at their initial value (which would be 0 if done right). Btw: your code does not create an array, so arr is null first of all.

In the end, the real answer is two-fold:

  • you are absolutely overburdening yourself here. Your code implies that you lack a lot of knowledge about basic java. You should spend some days, weeks, to learn Java first, before going for the even more complicated "Java Android"
  • you don't need an array to just find a max speed!

Simply do something like:

double maxSpeed = 0; // some field of your class, similar to your array

... wherever you determine the current speed:

if (maxSpeed > currentSpeed) {
  maxSpeed = currentSpeed;

Yet, when you want to store multiple datapoints, you either should create an array of a fixed size (where you start overwriting older values once you got to that fixed size), or you could use an ArrayList. That one grows dynamically, thus you could just keep adding values to it. (of course, at some point you better stop doing so, otherwise you will run out of memory sooner or later)

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks a lot but is it possible to store the values in an array and then find the highest speed using the math.max function. I know your method is much simpler but I just want to know if it is possible. – codeboy96 May 06 '19 at 09:32
  • hey for some reason it is still not displaying the max speed. – codeboy96 May 06 '19 at 10:40
  • @codeboy96 "For some reason" isn't something we can help with. First: read [mcve]. Then decide whether your "initial" question is addressed by my answer; then accept my answer and write a new question. Otherwise, you might want to edit your question and give us that: [mcve] ... – GhostCat May 06 '19 at 10:42
  • while traveling from point A to point B with my application my application crashes showing the message"unfortunately myapplication has stopped", and i cant open the logcat as to test it I have to go outside. – codeboy96 May 06 '19 at 10:56
  • @codeboy96 Probably because of that null pointer exception because your array is null, and not initialized. Again: we cant help you based on such information. Again: you are overburdening yourself. You are going way too fast. Write a simple java program that creates random values, and stores them. In pure java. Learn how to use an array, or an arraylist with pure java. Without all the android overhead. Honestly, you are like a person "Heho, I want to build a skyscraper ... but he, could somebody tell me how to hold the shuffle to dig the basement"? – GhostCat May 06 '19 at 11:00
  • @codeboy96 Read https://developer.android.com/topic/performance/vitals/crash for example. Or https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this ... please do **not** expect anyone here to sit down with you specifically to debug your app with you. **You** have to take the time to learn how debugging works on android. And as said: I suggest you forget about android for a few days. – GhostCat May 06 '19 at 11:04
  • I have removed the array I am using the code you suggested. – codeboy96 May 06 '19 at 11:05
  • I know how to debug it but I can't retrieve the stack trace as a cable cannot be connected to my computer while I am outside also its the code you suggested me so you may know what is wrong. – codeboy96 May 06 '19 at 11:14
  • Then see how you could use an emulator for example. And I already told you repeatedly: **your array is null**. You only declare it, you never ever **initialize** that array, like `arr = new double[100]`. Again: this is super basic stuff. Dont expect that people sit down with you to explain such things to you. At least not more than once. If you cant debug your android app, then learn how to do so. Or learn how to write UNIT tests that meaningfully test your code in an environment where you can debug it. – GhostCat May 06 '19 at 11:27
  • 1
    thanks for taking the time and patiently answering my queries and I will most definitely brush up with my basic java as you suggested. – codeboy96 May 07 '19 at 10:07
  • @codeboy96 I appreciate the quick comeback, and wish you all the best for your journey from hereon ;-) – GhostCat May 07 '19 at 10:08