I want to print the three values of each axes(scaledX , scaledY, scaledZ) of accelerometer in three TextView.
Can somebody help me?
thanks.
CODE:
MainActivity.java.
public class MainActivity extends Activity implements BluetoothAdapter.LeScanCallback {
private TextView mAccelerometerx, mAccelerometery, mAccelerometerz;
mAccelerometerx =(TextView) findViewById(R.id.ejex);
mAccelerometery =(TextView) findViewById(R.id.ejey);
mAccelerometerz =(TextView) findViewById(R.id.ejez);
private void updateAccelerometerValue(BluetoothGattCharacteristic characteristic ){
double accelerometerx = SensorTagData.extractAccelerometer(characteristic, mAccelerometerx);
double accelerometery = SensorTagData.extractAccelerometer(characteristic, mAccelerometery);
double accelerometerz = SensorTagData.extractAccelerometer(characteristic, mAccelerometerz);
mAccelerometerx.setText(String.format("%.4f", accelerometerx));
mAccelerometery.setText(String.format("%.4f", accelerometery));
mAccelerometerz.setText(String.format("%.4f", accelerometerz));
}
}
SensorData.java
public class SensorData {
public static double [] extractAccelerometer(BluetoothGattCharacteristic c) {
Integer x = c.getIntValue(FORMAT_SINT8, 0);
Integer y = c.getIntValue(FORMAT_SINT8, 1);
Integer z = c.getIntValue(FORMAT_SINT8, 2) * -1;
double scaledX = x / 64.0;
double scaledY = y / 64.0;
double scaledZ = z / 64.0;
return new double[] {scaledX, scaledY, scaledZ};
}
}
private void updateAccelerometerValue(BluetoothGattCharacteristic characteristic ){
double accelerometerx = SensorTagData.extractAccelerometer(characteristic, mAccelerometerx);
double accelerometery = SensorTagData.extractAccelerometer(characteristic, mAccelerometery);
double accelerometerz = SensorTagData.extractAccelerometer(characteristic, mAccelerometerz);
mAccelerometerx.setText(String.format("%.4f", accelerometerx)); //ERROR HERE
mAccelerometery.setText(String.format("%.4f", accelerometery)); //ERROR HERE
mAccelerometerz.setText(String.format("%.4f", accelerometerz)); //ERROR HERE
}
ERROR Type
The method extractAccelerometer(BluetoothGattCharacteristic) in the type SensorTagData is not applicable for the arguments (BluetoothGattCharacteristic, TextView)
I know I am giving more than two parameters, but if I delete "accelerometerx", "accelerometery" , "accelerometerz" the error disappears but I suppose will not see anything.
Related
I'm trying to build an app for fall detection using the accelerometer of a smartphone as a school project (so I still have a lot of things to improve).
I was doing some research and I found this article with some calculations, so I'm trying to turn those into some code.
I asked a friend for some help and he explained me how to do those calculations. But considering it's been a few years since I finished high school and I'm not very good at math, I'm sure I got some stuff wrong.
So I was expecting someone could give me a hand.
Here's what I need and what I have already, in case someone finds any mistake.
return Math.abs(x) + Math.abs(y) + Math.abs(z);
double anX = this.accelerometerValues.get(size -2).get(AccelerometerAxis.X) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.X);
double anY = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y);
double anZ = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z);
double an = anX + anY + anZ;
double anX0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.X), 2);
double anY0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y), 2);
double anZ0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z), 2);
double an0 = Math.sqrt(anX0 + anY0 + anZ0);
double anX1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.X), 2);
double anY1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y), 2);
double anZ1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z), 2);
double an1 = Math.sqrt(anX1 + anY1 + anZ1);
double a = an / (an0 * an1);
return (Math.pow(Math.cos(a), -1)) * (180 / Math.PI);
double aX = this.accelerometerValues.get(0).get(AccelerometerAxis.X) * this.accelerometerValues.get(3).get(AccelerometerAxis.X);
double aY = this.accelerometerValues.get(0).get(AccelerometerAxis.Y) * this.accelerometerValues.get(3).get(AccelerometerAxis.Y);
double aZ = this.accelerometerValues.get(0).get(AccelerometerAxis.Z) * this.accelerometerValues.get(3).get(AccelerometerAxis.Z);
double a0 = aX + aY + aZ;
double a1 = (Math.sqrt(Math.pow(aX, 2)) + Math.sqrt(Math.pow(aY, 2)) + Math.sqrt(Math.pow(aZ, 2)));
return (Math.pow(Math.cos(a0 / a1), -1)) * (180 / Math.PI);
I'm getting the same return from the second and the third calculation and neither seems to be the expected result, but I can't find what I'm doing wrong.
Here's the code for the class, for more details
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import br.com.aimcol.fallalertapp.activity.FallNotificationActivity;
import br.com.aimcol.fallalertapp.model.Elderly;
import br.com.aimcol.fallalertapp.model.Person;
import br.com.aimcol.fallalertapp.model.User;
import br.com.aimcol.fallalertapp.util.AccelerometerAxis;
import br.com.aimcol.fallalertapp.util.RuntimeTypeAdapterFactory;
public class FallDetectionService extends IntentService implements SensorEventListener {
private static final int ACCELEROMETER_SAMPLING_PERIOD = 1000000;
private static final double CSV_THRESHOLD = 23;
private static final double CAV_THRESHOLD = 18;
private static final double CCA_THRESHOLD = 65.5;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private User user;
private Gson gson;
private Long lastSentInMillis;
private Long minTimeToNotifyAgain = 3000000L;
private List<Map<AccelerometerAxis, Double>> accelerometerValues = new ArrayList<>();
public FallDetectionService() {
super(".FallDetectionService");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public FallDetectionService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public final void onAccuracyChanged(Sensor sensor,
int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// Axis of the rotation sample, not normalized yet.
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
if (this.isFallDetected(x, y, z)) {
if (this.isOkayToNotifyAgain()) {
this.lastSentInMillis = System.currentTimeMillis();
Toast.makeText(this, "Fall", Toast.LENGTH_LONG).show();
FallNotificationActivity.startFallNotificationActivity(this, this.gson.toJson(this.user));
}
}
}
private boolean isFallDetected(double x,
double y,
double z) {
double acceleration = this.calculateAcceleration(x, y, z);// - SensorManager.GRAVITY_EARTH;
this.addAccelerometerValuesToList(x, y, z, acceleration);
String msg = new StringBuilder("x: ").append(x).append(" y: ").append(y).append(" z: ").append(z).append(" acc: ").append(acceleration).toString();
Log.d("FDS-Acc-Values", msg);
if (acceleration > CSV_THRESHOLD) {
// double angleVariation = this.calculateAngleVariation();
// if (angleVariation > CAV_THRESHOLD) {
// double changeInAngle = this.calculateChangeInAngle();
// if (changeInAngle > CCA_THRESHOLD) {
Log.d("FDS-Fall-Happened", msg);
return true;
// }
// }
}
return false;
}
private void addAccelerometerValuesToList(double x,
double y,
double z,
double acceleration) {
if(this.accelerometerValues.size() >= 4) {
this.accelerometerValues.remove(0);
}
Map<AccelerometerAxis, Double> map = new HashMap<>();
map.put(AccelerometerAxis.X, x);
map.put(AccelerometerAxis.Y, y);
map.put(AccelerometerAxis.Z, z);
map.put(AccelerometerAxis.ACCELERATION, acceleration);
this.accelerometerValues.add(map);
}
private double calculateAcceleration(double x,
double y,
double z) {
return Math.abs(x) + Math.abs(y) + Math.abs(z);
}
private double calculateAngleVariation() {
int size = this.accelerometerValues.size();
if (size < 2){
return -1;
}
double anX = this.accelerometerValues.get(size -2).get(AccelerometerAxis.X) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.X);
double anY = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y);
double anZ = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z);
double an = anX + anY + anZ;
// double an = this.accelerometerValues.get(size -2).get(AccelerometerAxis.ACCELERATION) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.ACCELERATION);
double anX0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.X), 2);
double anY0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y), 2);
double anZ0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z), 2);
double an0 = Math.sqrt(anX0 + anY0 + anZ0);
double anX1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.X), 2);
double anY1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y), 2);
double anZ1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z), 2);
double an1 = Math.sqrt(anX1 + anY1 + anZ1);
double a = an / (an0 * an1);
return (Math.pow(Math.cos(a), -1)) * (180 / Math.PI); //cosseno inverso? Ou cosseno ^-1?
}
private double calculateChangeInAngle() {
int size = this.accelerometerValues.size();
if (size < 4){
return -1;
}
double aX = this.accelerometerValues.get(0).get(AccelerometerAxis.X) * this.accelerometerValues.get(3).get(AccelerometerAxis.X);
double aY = this.accelerometerValues.get(0).get(AccelerometerAxis.Y) * this.accelerometerValues.get(3).get(AccelerometerAxis.Y);
double aZ = this.accelerometerValues.get(0).get(AccelerometerAxis.Z) * this.accelerometerValues.get(3).get(AccelerometerAxis.Z);
double a0 = aX + aY + aZ;
double a1 = (Math.sqrt(Math.pow(aX, 2)) + Math.sqrt(Math.pow(aY, 2)) + Math.sqrt(Math.pow(aZ, 2)));
return (Math.pow(Math.cos(a0 / a1), -1)) * (180 / Math.PI);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (this.user == null) {
String userJson = intent.getStringExtra(User.USER_JSON);
this.user = this.gson.fromJson(userJson, User.class);
}
}
#Override
public int onStartCommand(Intent intent,
int flags,
int startId) {
if (this.gson == null) {
RuntimeTypeAdapterFactory<Person> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
.of(Person.class, "type")
.registerSubtype(Elderly.class, Elderly.class.getSimpleName());
this.gson = new GsonBuilder().registerTypeAdapterFactory(runtimeTypeAdapterFactory).create();
}
if (this.user == null) {
String userJson = intent.getStringExtra(User.USER_JSON);
this.user = this.gson.fromJson(userJson, User.class);
}
this.mSensorManager = (SensorManager) super.getSystemService(Context.SENSOR_SERVICE);
this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (this.mAccelerometer == null) {
throw new RuntimeException("Acelerometro não encontrado");
}
this.mSensorManager.registerListener(this, this.mAccelerometer, ACCELEROMETER_SAMPLING_PERIOD);
return Service.START_STICKY;
}
private boolean isOkayToNotifyAgain() {
return this.lastSentInMillis == null || (this.lastSentInMillis + this.minTimeToNotifyAgain) < System.currentTimeMillis();
}
public static void startFallDetectionService(String userJson,
Context context) {
Intent fallDetectionServiceIntent = new Intent(context, FallDetectionService.class);
fallDetectionServiceIntent.putExtra(User.USER_JSON, userJson);
context.startService(fallDetectionServiceIntent);
}
#VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
protected boolean testFallDetection(List<Map<AccelerometerAxis, Double>> values) {
for (Map<AccelerometerAxis, Double> value : values) {
if (this.isFallDetected(
value.get(AccelerometerAxis.X),
value.get(AccelerometerAxis.Y),
value.get(AccelerometerAxis.Z))) {
return true;
}
}
return false;
}
}
Ps: Sorry if I got something wrong. English is not my first language and I'm a little rusty.
Ps2: Sorry about my variable names.
Ps3: The code is on github, if you want to take a look on the rest of the code or if instead of posting a reply here you want to make a pull request or something, feel free.
This question might not be appropriate here. SO isn't intended as a code review site.
Here are a few comments to consider:
The first formula you list is not what you've expressed in code. There is no square root or sum of squares in the formula, but you put them into code for some reason. The article says SV should be the sum of the absolute value of the components of the linear acceleration vector. That's not what your code says.
The meaning of n and n+1 in the second formula isn't clear to me. Are those consecutive time points? The dot product of two vectors is easy to calculate - but for which two vectors?
The third formula calls for an average of acceleration vectors over a four second window. I don't see that being done anywhere. The number of vectors involved in the average would depend on your sampling rate.
I would suggest that you re-read the article several more times.
I'd also advise that you encapsulate these into functions and write some good unit tests for them. See if you can reproduce the results from the paper.
new to programming i know i'm doing something that's probably really obviously wrong to do with passing or using the wrong variables but i just can't work out what.
Here is my code:
public class CameraViewActivity extends Activity implements
SurfaceHolder.Callback, OnLocationChangedListener, OnAzimuthChangedListener {
private double mAzimuthReal = 0;
private double mAzimuthTheoretical = 0;
private static double AZIMUTH_ACCURACY = 5;
private double mMyLatitude = 0;
private double mMyLongitude = 0;
private List<Double> calculateAzimuthAccuracy(double azimuth) {
double minAngle = azimuth - AZIMUTH_ACCURACY;
double maxAngle = azimuth + AZIMUTH_ACCURACY;
List<Double> minMax = new ArrayList<Double>();
#Override
public void onAzimuthChanged(float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTheoretical = calculateTheoreticalAzimuth();
pointerIcon = (ImageView) findViewById(R.id.icon);
double minAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(1);
if (isBetween(minAngle, maxAngle, mAzimuthReaal) {
pointerIcon.setVisibility(View.VISIBLE);
}
else {
pointerIcon.setVisibility(View.INVISIBLE);
}
updateDescription();
}
Thanks for reading
Use
isRange(mMyLatitude, mMyLongitude, mPoi.getPoiLatitude(), mPoi.getPoiLongitude)
instead of
isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude)
FYI, its better to use small letter for naming variable.
In this function you need to pass as paramters either two locations and use their coordinates in the function inRange or you pass four coordinates and use them.
public void onAzimuthChanged(float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTheoretical = calculateTheoreticalAzimuth();
pointerIcon = (ImageView) findViewById(R.id.icon);
double minAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(1);
if (isBetween(minAngle, maxAngle, mAzimuthReal) && isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude)) {
pointerIcon.setVisibility(View.VISIBLE);
}
else {
pointerIcon.setVisibility(View.INVISIBLE);
}
updateDescription();
}
This has no meaning
isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude);
One more thing, adapt a professional naming criteria. Giving your attributes names that start with capital letters is quite MEH.
Writing a program in Android Studio 2.2.2 (MainActivity.java). Basically there are multiple inputs, one button, multiple outputs. However, many of the outputs are cross referenced into many of the other outputs. I'm new to all of this as our professor threw this on us in a non-programming class. Can anyone see some of my errors? I hope that I'm doing the process mostly correct, but the operations are all have issues with string/float/double incompatibilities. Thanks for any insight!
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCalc;
private TextView tvaResult;
private TextView tvcResult;
private TextView tvetResult;
private TextView tvphiResult;
private TextView tvMnResult;
private TextView tvphiMnResult;
private TextView tvbeta1Result;
private EditText etB,etD,etH,etAs,etFc,etFy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btnCalc = (Button)findViewById(R.id.btnCalc);
etB = (EditText)findViewById(R.id.etB);
etD = (EditText)findViewById(R.id.etD);
etH = (EditText)findViewById(R.id.etH);
etAs = (EditText)findViewById(R.id.etAs);
etFc = (EditText)findViewById(R.id.etFc);
etFy = (EditText)findViewById(R.id.etFy);
tvaResult = (TextView)findViewById(R.id.tvaResult);
tvcResult = (TextView)findViewById(R.id.tvcResult);
tvetResult = (TextView)findViewById(R.id.tvetResult);
tvphiResult = (TextView)findViewById(R.id.tvphiResult);
tvMnResult = (TextView)findViewById(R.id.tvMnResult);
tvphiMnResult = (TextView)findViewById(R.id.tvphiMnResult);
tvbeta1Result = (TextView)findViewById(R.id.tvbeta1Result);
btnCalc.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Float B = Float.parseFloat(etB.getText().toString());
Float D = Float.parseFloat(etD.getText().toString());
Float H = Float.parseFloat(etH.getText().toString());
Float As = Float.parseFloat(etAs.getText().toString());
Float Fc = Float.parseFloat(etFc.getText().toString());
Float Fy = Float.parseFloat(etFy.getText().toString());
Float aResult = Float.parseFloat(tvaResult.getText().toString());
Float cResult = Float.parseFloat(tvcResult.getText().toString());
Float etResult = Float.parseFloat(tvetResult.getText().toString());
Float beta1Result = Float.parseFloat(tvbeta1Result.getText().toString());
Float phiResult = Float.parseFloat(tvphiResult.getText().toString());
switch(view.getId() ) {
case R.id.btnCalc:
tvaResult = (Fy * As) / (0.85 * Fc * B);
tvcResult = aResult / beta1Result;
tvetResult = ((D - cResult) / (cResult)) * 0.003;
if (Fc <= 4000) {
beta1Result = 0.85;
} else if (4000 < Fc <= 8000) {
beta1Result= ((0.85)-(0.05 * ((Fc - 4000) / (1000))));
} else {
beta1Result= 0.65;
}
if (etResult >= 0.005) {
tvphiResult= 0.9;
} else if (0.002 <= etResult < 0.005) {
tvphiResult= 0.65 + ((etResult - 0.002) * ((0.25) / (0.005 - 0.002)));
} else {
tvphiResult= 0.00
}
tvMnResult= (Fy * As) * (etD - (aResult / 2));
tvphiMnResult= phiResult * tvMnResult
}}
}}
To make it short, you need to keep the type of each Variable.
Here for example :
tvaResult = (Fy * As) / (0.85 * Fc * B);
You have
TextView = (Float * Float) / ( Double * Float * Float)
TextView = Double // Not possible
You are trying to put a Float value into a Instance of TextView, this can't be done of course. But you really want to update the text of the Textview, so use the methods setText(String) of TextView like :
tvaResult.setText((Fy * As) / (0.85 * Fc * B) + ""); // Need to be convert into String
To change the text to print
This is basicly always the same mistake done, you need to change the text of the TextView an not trying to change the instance itself.
So I am currently working on an android project and I got stuck at some point; here is the code:
public class Readiness {
private Double examAverageReadiness;
private Integer courseReadiness;
private Integer courseScore;
public Integer courseCount;
//Set the number of courses offered
private void setCourseCount(Integer c) {
courseCount = c;
}
//Get readiness for individual course examinations
//'a' and 'b' are the course test scores
public Integer getCourseReadiness(Integer a, Integer b) {
Integer c = (a/15) * 100;
Integer d = (b/15) * 100;
Integer e = (c+d)/2;
//Double f = Double.parseDouble(e.toString());
courseReadiness = e;
return e;
}
//Get a predicted score in a course examination
public Integer getPredictableCourseScore(Integer a, Integer b) {
Integer r = (courseReadiness/100) * 70;
Integer i = r.intValue();
Integer d = i + a + b;
courseScore = d;
return d;
}
//This is the total readiness for a semester examination
public Double examRValue(Double tmc121, Double eds121, Double gst121, Double
gst122, Double cst121)
{
Double v = ((tmc121+eds121+gst121+gst122+cst121)/(courseCount*100)) * 100;
examAverageReadiness = v;
return v;
}
}
I then used it here:
private View.OnClickListener onClicke=new View.OnClickListener() {
public void onClick(View v){
EditText edtTxt = (EditText)findViewById(R.id.edtTxt);
edtTxt.setText("hello there!");
Readiness r = new Readiness();
r.courseCount = 5;
//TMC 121
EditText one = (EditText)findViewById(R.id.v1);
EditText two = (EditText)findViewById(R.id.v2);
Integer one1 = Integer.parseInt(one.getText().toString());
Integer two2 = Integer.parseInt(two.getText().toString());
Integer p = r.getCourseReadiness(one1, two2);
Log.d("pdsk", p.toString());
Integer f = r.getPredictableCourseScore(one1, two2);
TextView tmc = (TextView)findViewById(R.id.tmc121);
tmc.setText("Readiness: " + p.toString() + "% ExamScore: " + f);
//EDS 121
EditText three = (EditText)findViewById(R.id.v3);
EditText four = (EditText)findViewById(R.id.v4);
Integer three3 = Integer.parseInt(three.getText().toString());
Integer four4 = Integer.parseInt(four.getText().toString());
Integer e = r.getCourseReadiness(three3, four4);
Integer s = r.getPredictableCourseScore(three3, four4);
TextView eds = (TextView)findViewById(R.id.eds121);
eds.setText("Readiness: " + e.toString() + "% ExamScore: " + s);
}
}
This was okay to me until I debugged it and found out that the Readiness.java class's method -
"getCourseReadiness(integer a, integer b)"
always returned a 0 (zero) value. This is kinda annoying you know (to me though...) because I expect a non-zero value if I place a non-zero value in the EditText field. So please I hope I can get answers from this platform... (Thanks).
I am getting my speed from the gps using location.speed() function and the value is getting stored in nCurrentSpeed.
Should i store the nCurrentSpeed value in an Array to get the average speed when the app has stopped? How do i do it?
#Override
public void onLocationChanged(Location location) {
TextView dis =(TextView)findViewById(R.id.distance);
TextView time1 =(TextView)findViewById(R.id.time);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "SPEEDOFONT.TTF");
text2 = (TextView) findViewById(R.id.text2);
text2.setTypeface(myTypeface);
float speed,time, distance;
if (location == null) {
text2.setText("-.- km/h");
} else {
float nCurrentSpeed = location.getSpeed();
speed = (float) (nCurrentSpeed * 3.6);
text2.setText(String.format("%.2f km/h", speed));
time =location.getTime();
time1.setText("" +time);
distance = speed*time;
dis.setText(String.format("%.2f m/s", distance));
}
}
It may not be spot on to the actual (very specific) question, but you could also use DoubleSummaryStatistics: You can create an instance of this class, then let it accept one value after the other, and finally get the average without doing manual computations - and by the way, you get the computation of the minimum and maximum for free.
private final DoubleSummaryStatistics stats = new DoubleSummaryStatistics();
public void onLocationChanged(Location location)
{
...
float speed = ...;
stats.accept(speed);
}
void printSummary()
{
double average = stats.getAverage();
double min = stats.getMin();
double max = stats.getMax();
...
}
EDIT:
In case you don't use Java 8 yet, you can do
private final List<Float> speeds = new ArrayList<Float>();
public void onLocationChanged(Location location)
{
...
float speed = ...;
speeds.add(speed);
}
private float computeAverage(List<Float> values)
{
float sum = 0;
for (Float v : values)
{
sum += v;
}
return sum / values.size();
}
void printSummary()
{
double average = computeAverage(speeds);
...
}
(Similar to what #AndrewTobilko originally proposed)