Android - Accelerometer fall detection algorithm - java

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.

Related

EventDispatchThread Execption

I create alist method to insert principal values and remaining balances according to the payments.But when I implement this method in actionListner method error occurs(EventDispatchThread Execption).I try to solve it.Please give any help for me to solve this.
public class Loan {
float lamt,irate,inst,lbalance;
int duration,nop;
String amtlist[][] = new String[duration+1][5];
Loan(float lamt, float irate, int duration, int nop) {
this.lamt = lamt;
this.irate = irate;
this.duration = duration;
this.nop = nop;
}
public void alist() {
amtlist[0][0] = "0" ;
amtlist[0][1] = "0";
amtlist[0][2] = "0";
amtlist[0][3] = "0";
amtlist[0][4] = Float.toString(inst*annuity(duration,irate));
float v = 1 / (1 + irate);
for (int i = 1; i < duration + 1; i++) {
amtlist[i][0] = Float.toString(i);
amtlist[i][1] = Float.toString(irate * annuity(duration + 1 - i, irate));
amtlist[i][2] = Float.toString(instalment());
amtlist[i][3] = Double.toString(instalment() * Math.pow(v, i));
amtlist[i][4] = Float.toString(instalment() * annuity(duration - i, irate));
}
}
public float annuity(int duration, float irate) {
float v = 1 / (1 + irate);
float an = (float) ((1 - Math.pow(v, duration)) / irate);
return an;
}
public float instalment(){
return inst = lamt / annuity(duration, irate);
}
public float lbalance() {
return lbalance = inst * annuity(duration - nop, irate);
}
}
public void actionPerformed(ActionEvent e) {
String lamtstr = tf1.getText();
String iratestr = tf2.getText();
String durationstr = tf3.getText();
String nopstr = tf4.getText();
float lamt = Float.parseFloat(lamtstr);
float irate = Float.parseFloat(iratestr);
int duration = Integer.parseInt(durationstr);
int nop = Integer.parseInt(nopstr);
Loan l = new Loan(lamt, irate, duration, nop);
float inst = 0, balance = 0;
if (e.getSource() == b1) {
inst =l.instalment();
balance =l.lbalance();
}
if (e.getSource() == b2) {
l.alist();
fscr.dispose();
new AmTable(l.amtlist);
}
tf5.setText(String.valueOf(inst));
tf6.setText(String.valueOf(balance));
}
I tried solve it by changing alist method to value returning method but my attempt got vain.
if (e.getSource() == b2) {
l.alist();
fscr.dispose();
new AmTable(l.amtlist);
}
I expected to call AmTable function with amlist array.

How to recreate the exact RSI calculation from tradingview in java?

I have read every related post on stackoverflow but i just still cant seem to replicate the exact same RSI calculation that tradingview uses. I've spend over dozens of hours trying to get this right. At this point it is really sucking the joy out of my hobby project. Any help would be greatly appreciated.
If any other info or something is required please let me know and i will add it.
What the tradingview documentation says about how the calculation is done:
* For a practical example, the built-in Pine Script function rsi(), could be replicated in long form as follows.
* change = change(close)
* gain = change >= 0 ? change : 0.0
* loss = change < 0 ? (-1) * change : 0.0
* avgGain = rma(gain, 14)
* avgLoss = rma(loss, 14)
* rs = avgGain / avgLoss
* rsi = 100 - (100 / (1 + rs))
*
*
* where
* RMA = alpha * source + (1-alpha) * RMA[1]
* alpha = 1/length
I just cant seem to get the RMA part right, i just dont have a clue anymore on how to interperted it. Below is my class with at the bottom some sample data. If someone has managed to get a exact or near RSI calculation to to the tradingview could you please walk me through the steps.
Rsi_indicator.class
public class Rsi_indicator {
static Candlestick[] candles = getCandleSticks();
static double[] gain_array = new double[candles.length];
static double[] loss_array = new double[candles.length];
public static final int RSI_PERIOD = 14;
public static void main(String[] args) {
/**
* 1. Calculate change over closes
*
* */
for (int i = 0; i < candles.length; i++) {
double gain = 0;
double loss = 0;
if (i >= 1) {
double change = candles[i - 1].getClose() - candles[i].getClose();
gain_array[i] = change >= 0 ? change : 0.0d;
loss_array[i] = change < 0 ? (-1) * change : 0.0d;
}
}
/**
* 2. Calculate AVG gain
*
* According to trading view they use this --> avgGain = rma(gain, 14)
* Where
* RMA = alpha * source + (1-alpha) * RMA[1]
* alpha = 1/length
*/
double alpha = 1.0 / RSI_PERIOD;
RMA rma_gain = new RMA(alpha);
RMA rma_loss = new RMA(alpha);
/*
TODO HOW EXACTLY TO IMPLEMENT THE ABOVE RMA?
what is exactly meant by source ? and RMA[1] is this the previous value that was calculated?
*/
/**
* 4. Calculate relative strength
* */
double RS = avg_gain / avg_loss;
/**
* 5. Calculate RSI
* */
double rsi = 100 - (100 / (1 + RS));
/**
* The last 4 calculated rsi values should be:
* 7 nov 2021 --> 59.68
* 8 nov 2021 --> 67.65
* 9 nov 2021 --> 65.75
* 10 nov 2021 --> 59.33
*/
System.out.println("RSI: " + rsi);
}
static class RMA {
private double alpha;
private Double oldValue;
public RMA(double alpha) {
this.alpha = alpha;
}
public double average(double value) {
if (oldValue == null) {
oldValue = value;
return value;
}
double newValue = oldValue + alpha * (value - oldValue);
return newValue;
}}
/**
* This is just for you to have a working sample instantly
* The sample data i pulled from the binance api is the
* 1D BINANCE BTCUSDT pair from 2021-10-20T02:00 TO 2021-11-10T01:00.
*/
static Candlestick[] getCandleSticks() {
String[] data =
{"1634688000000,64280.59,67000.0,63481.4,66001.41,1634774399999",
"1634774400000,66001.4,66639.74,62000.0,62193.15,1634860799999",
"1634860800000,62193.15,63732.39,60000.0,60688.22,1634947199999",
"1634947200000,60688.23,61747.64,59562.15,61286.75,1635033599999",
"1635033600000,61286.75,61500.0,59510.63,60852.22,1635119999999",
"1635120000000,60852.22,63710.63,60650.0,63078.78,1635206399999",
"1635206400000,63078.78,63293.48,59817.55,60328.81,1635292799999",
"1635292800000,60328.81,61496.0,58000.0,58413.44,1635379199999",
"1635379200000,58413.44,62499.0,57820.0,60575.89,1635465599999",
"1635465600000,60575.9,62980.0,60174.81,62253.71,1635551999999",
"1635552000000,62253.7,62359.25,60673.0,61859.19,1635638399999",
"1635638400000,61859.19,62405.3,59945.36,61299.8,1635724799999",
"1635724800000,61299.81,62437.74,59405.0,60911.11,1635811199999",
"1635811200000,60911.12,64270.0,60624.68,63219.99,1635897599999",
"1635897600000,63220.57,63500.0,60382.76,62896.48,1635983999999",
"1635984000000,62896.49,63086.31,60677.01,61395.01,1636070399999",
"1636070400000,61395.01,62595.72,60721.0,60937.12,1636156799999",
"1636156800000,60940.18,61560.49,60050.0,61470.61,1636243199999",
"1636243200000,61470.62,63286.35,61322.78,63273.59,1636329599999",
"1636329600000,63273.58,67789.0,63273.58,67525.83,1636415999999",
"1636416000000,67525.82,68524.25,66222.4,66947.66,1636502399999",
"1636502400000,66947.67,69000.0,62822.9,64882.43,1636588799999",
};
List<Candlestick>list = new ArrayList<>();
for (String s: data) {
Candlestick c = new Candlestick();
String[] sArr = s.split(",");
c.setOpenTime(Long.valueOf(sArr[0]));
c.setOpen(sArr[1]);
c.setHigh(sArr[2]);
c.setLow(sArr[3]);
c.setClose(sArr[4]);
c.setCloseTime(Long.valueOf(sArr[5]));
list.add(c);
}
return list.stream().toArray(Candlestick[]::new);
}
}
Candlestick.class
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Candlestick {
private Long openTime;
private double open;
private double high;
private double low;
private double close;
private double volume;
private Long closeTime;
public Long getOpenTime() {
return openTime;
}
public void setOpenTime(Long openTime) {
this.openTime = openTime;
}
public double getOpen() {
return open;
}
public void setOpen(String open) {
this.open = toDouble(open);
}
public double getHigh() {
return high;
}
public void setHigh(String high) {
this.high = toDouble(high);
}
public double getLow() {
return low;
}
public void setLow(String low) {
this.low = toDouble(low);
}
public double getClose() {
return close;
}
public void setClose(String close) {
this.close = toDouble(close);
}
public Long getCloseTime() {
return closeTime;
}
public void setCloseTime(Long closeTime) {
this.closeTime = closeTime;
}
public LocalDateTime getFormattedOpenTime() {
return Instant.ofEpochMilli(openTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
public LocalDateTime getFormattedCloseTime() {
return Instant.ofEpochMilli(closeTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
public double toDouble(String a) {
return Double.parseDouble(a);
}
}

Converting to Float for Math Operations

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.

Do not make a double loop (While) as HasNext ()?

this code is double while loop ! but not double... only one loop > The end..
plz help me..
i want a double loop for while..
do not double loop for hasNext()?
---------------------------edit--------------
I'm sorry. I've made ​​a mistake Clumsy English.
"Do not make a double loop (While) as HasNext ()?" What I'm asking.
Sorry, I did not polite.
Put the "While" he "HasNext ()" not been able to repeat the first loop.
I'd like to create like multiplication like. Please help me.
import java.io.IOException;
import java.net.MalformedURLException;
import org.geotools.data.shapefile.files.ShpFiles;
import org.geotools.data.shapefile.shp.ShapefileException;
import org.geotools.data.shapefile.shp.ShapefileReader;
import org.geotools.data.shapefile.shp.ShapefileReader.Record;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
class Point {
double x;
double y;
Point(double x2, double y2) {
this.x = x2;
this.y = y2;
}
static double distance(Point p1, Point p2) {
double dist;
dist = Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
return dist;
}
}
public class KFunction {
private static double X;
private static double Y;
private static double X1;
private static double Y1;
public static void main(String[] args) {
ShapefileReader r = null;
ShapefileReader r2 = null;
try {
ShpFiles shpFile = new ShpFiles("Juvenile_Offenders_in_Cardiff.shp");
ShpFiles shpFile2 = new ShpFiles("Juvenile_Offenders_in_Cardiff.shp");
GeometryFactory geometryFactory = new GeometryFactory();
r = new ShapefileReader(shpFile, true, false, geometryFactory);
r2 = new ShapefileReader(shpFile2, true, false, geometryFactory);
Record record2 = r2.nextRecord();
Geometry shape2 = (Geometry) record2.shape();
com.vividsolutions.jts.geom.Point centroid2 = shape2.getCentroid();
int i = 0;
boolean A = r2.hasNext();
while (A) {
X = centroid2.getX();
Y = centroid2.getY();
while (r.hasNext()) {
System.out.println("No." + i);
Record record = r.nextRecord();
Geometry shape = (Geometry) record.shape();
com.vividsolutions.jts.geom.Point centroid = shape.getCentroid();
X1 = centroid.getX();
Y1 = centroid.getY();
Point p1 = new Point(X, Y);
Point p2 = new Point(X1, Y1);
double result = Point.distance(p1, p2);
System.out.println("X : " + X + " Y : " + Y + " X1 : " + X1 + " Y1 : " + Y1);
System.out.println("두 점 사이의 거리 : " + result);
System.out.println("---------------------------");
i++;
}
break;
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ShapefileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
To me it looks like the outer loop while(A) would either be done not at all or forever since it appears the A never changes inside of it.

Android Application Crashing When achartengine graph is called upon

I wrote a practice app that solves quadratic equations and now I want to have the option to graph them with a button. Yet when I press the button the application crashes. Here is the code for the main program and the graphing one(located beneath):
Main class: *note: I do have the necessary classes imported and the .jar.
package com.test.quad;
import java.text.DecimalFormat;
import java.util.List;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class QuadraticActivity extends Activity {
Button reset;
Button solve;
Button grapher;
TextView labela1;
TextView b1label;
TextView c1label;
TextView result1;
TextView result2;
EditText a1;
EditText b1;
EditText c1;
public List<double[]> x,y;
public double a, b, c;
public double xStart = 0, xEnd = 0;
public double xCurrent;
double yCurrent;
public double xStep;
public int count = 100;
Graph g = new Graph();
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
labela1 = (TextView)this.findViewById(R.id.labela1);
b1label = (TextView)this.findViewById(R.id.b1label);
c1label = (TextView)this.findViewById(R.id.c1label);
result1 = (TextView)this.findViewById(R.id.result1);
result2 = (TextView)this.findViewById(R.id.result2);
a1 = (EditText)this.findViewById(R.id.a1);
b1 = (EditText)this.findViewById(R.id.b1);
c1 = (EditText)this.findViewById(R.id.c1);
solve = (Button)this.findViewById(R.id.solve);
reset = (Button)this.findViewById(R.id.reset);
grapher = (Button)this.findViewById(R.id.grapher);
}
public void onClickHandler(View v) {
switch(v.getId()){
case R.id.reset:
a1.setText("");
b1.setText("");
c1.setText("");
result1.setText("");
result2.setText("");
a=0;
b=0;
c=0;
break;
case R.id.solve:
solveEquation();
break;
case R.id.grapher:
Intent achartIntent = new Graph().execute(this);
startActivity(achartIntent);
Log.d("debug", "clicked" );
break;
}
}
protected void solveEquation() {
try{
a = Double.parseDouble(a1.getText().toString());
b = Double.parseDouble(b1.getText().toString());
c = Double.parseDouble(c1.getText().toString());
}
catch (NumberFormatException exception) {
result1.setText("Please enter a number");
result2.setText(" ");
}
finally{}
if (a==0 && b==0 && c==0){
result1.setText(" ");
result2.setText(" ");
}
else{
double yy, xx,x1, x2, x3;
double disc = (( b * b) - (4 * a * c));
DecimalFormat fmt = new DecimalFormat("0.###");
if (disc > 0){
double solution1 = ((-1 * b) - Math.sqrt(disc)) / ( 2 * a);
double solution2 = ((-1 * b) + Math.sqrt(disc)) / (2 * a);
result1.setText("Solution #1: " + fmt.format(solution1));
result2.setText("Solution #2: " + fmt.format(solution2));
if (solution1 < solution2){
xStart = solution1 - 5;
xEnd = solution2 + 5;
}
else{
xStart = solution2 - 5;
xEnd = solution1 + 5;
}
}
else if (disc == 0){
double oneSol = (-1 * b) / ( 2 * a);
result1.setText("One Solution: " + fmt.format(oneSol));
result2.setText("");
xStart = oneSol - 5;
xEnd = oneSol + 5;
}
else{
yy = (-1 * b) / (2 * a);
xx = ((b * b) - (4 * a * c));
x1 = Math.abs(xx);
x2 = Math.sqrt(x1);
x3 = (x2) / (2 * a);
result1.setText("Imaginary Solution #1: " + fmt.format(yy) + " - " +
fmt.format(x3)+"i" );
result2.setText("Imaginary Solution #2: " + fmt.format(yy) + " + " +
fmt.format(x3)+"i" );
xStart = (((-1 * b) - (x2)) / ( 2 * a)) - 5;
xEnd = (((-1 * b) + (x2)) / (2 * a)) + 5;
}
}
}
}
and the graph code:
package com.test.quad;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
/**
* Quadratic
*/
public class Graph extends AbstractDemoChart {
/**
* Returns the chart name.
* #return the chart name
*/
public String getName() {
return "Quadratic Functions";
}
/**
* Returns the chart description.
* #return the chart description
*/
public String getDesc() {
return "Quadratic Graph";
}
/**
* Executes the chart demo.
* #param context the context
* #return the built intent
*/
public Intent execute(Context context) {
String[] titles = new String[] { "Function" };
List<double[]> x = new ArrayList<double[]>();
List<double[]> values = new ArrayList<double[]>();
QuadraticActivity c = new QuadraticActivity();
double range = c.xEnd - c.xStart;
double step = .01 * range;
int count = 110;
double xCurrent = c.xStart;
double[] xValueArr = new double[count];
double[] yValueArr = new double[count];
values.add(xValueArr);
values.add(yValueArr);
for (int ii=0; xCurrent <= c.xEnd; xCurrent += step, ii++) {
double yCurrent = (c.a)*Math.pow(xCurrent, 2) + (c.b)*xCurrent + (c.c);
xValueArr[ii] = xCurrent;
yValueArr[ii] = yCurrent;
}
System.out.println(x);
int [] colors = new int[] { Color.BLUE };
PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
setChartSettings(renderer, "Graph of Quadratic Equation", "X", "Y", 0, 360, -1, 1,
Color.GRAY, Color.LTGRAY);
renderer.setXLabels(20);
renderer.setYLabels(10);
return ChartFactory.getLineChartIntent(context, buildDataset(titles, x, values),
renderer);
}
}
Add the the activity GraphicalActivity to the manifest file:
<activity android:name="org.achartengine.GraphicalActivity" />

Categories

Resources