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.
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.
I'm having trouble passing the updated values of initial_guess_1 and initial_guess_2 back into the GoldenSectionSearch method (I've attempted to have the method call itself until the terminating condition associated with the "if" is satisfied). My attempts at resolving this myself were influenced by what I found here:
https://softwareengineering.stackexchange.com/questions/286008/parameters-are-passed-by-value-but-editing-them-will-edit-the-actual-object-li
http://www.java-tutorial.com/java-tutorial/java-classes-methods/java-call-reference/
I'm still unable to figure out what I am doing wrong in trying to pass updated values back into the method. What am I doing wrong and how do I fix it? I'm a novice at programming and would like things broken down into the smallest,most easily understood terms possible.
public static double GoldenSectionSearch(double x_1, double x_2, double initial_guess_1,double initial_guess_2 ,double gradient_x, double gradient_y, double a,double a_0,double a_1,double a_2,double b_0,double b_1,double p,double N){
//Stuff
if(Math.abs((100*(x_2 - x_1*x_1)*(x_2 - x_1*x_1) + (1- x_1)*(1- x_1)) - (100*(initial_guess_2 - initial_guess_1*initial_guess_1)*(initial_guess_2 - initial_guess_1*initial_guess_1) + (1- initial_guess_1)*(1- initial_guess_1)) )/Math.abs(1+(100*(initial_guess_2 - initial_guess_1*initial_guess_1)*(initial_guess_2 - initial_guess_1*initial_guess_1) + (1- initial_guess_1)*(1- initial_guess_1))) >=0.50*Math.pow(10,-6)){
initial_guess_1=x_1;
initial_guess_2=x_2;
//Double Boxed_a = new Double(a);
Double Boxed_initial_guess_1 = new Double(initial_guess_1);
Double Boxed_initial_guess_2 = new Double(initial_guess_2);
initial_guess_1.GoldenSectionSearch(initial_guess_1);
initial_guess_2.GoldenSectionSearch(initial_guess_2);
gradient_x = (400*initial_guess_1*(initial_guess_1*initial_guess_1 - initial_guess_2) + 2*(initial_guess_1 -1));
gradient_y = (200*(initial_guess_2 - initial_guess_1*initial_guess_1));
GoldenSectionSearch(initial_guess_1,initial_guess_2,x_1, x_2, gradient_x, gradient_y, a, a_0, a_1, a_2, b_0, b_1, p,N);
} else{
double f_x=(100*(x_2 - x_1*x_1)*(x_2 - x_1*x_1) + (1- x_1)*(1- x_1));
System.out.print("alpha = " + a + " " + "x_1 = " + x_1 + " " + "x_2 = " + x_2 + " " + "f_x = " + f_x);
}
// Double Boxed_a = new Double(a);
return x_2;
}
You can't modify primitives. You have to create wrapper class with getters/setters
public class MyWrapperObject {
private double x_1;
private double x_2;
private double initial_guess_1;
private double initial_guess_2;
private double gradient_x;
private double gradient_y;
private double a;
private double a_0;
private double a_1;
private double a_2;
private double b_0;
private double b_1;
private double p;
private double N;
public double getX_1() {
return x_1;
}
public void setX_1(double x_1) {
this.x_1 = x_1;
}
/* The rest of getters/setters */
}
than pass it to your method and use it like
public static double GoldenSectionSearch(MyWrapperObject obj){
// ...
double initial_guess_1 = obj.get_initial_guess_1();
double initial_guess_2 = obj.get_initial_guess_2();
obj.setGradient_x(400*initial_guess_1*(initial_guess_1*initial_guess_1 - initial_guess_2) + 2*(initial_guess_1 -1));
// ...
}
There is also a question here on SO whether java is pass-by-reference or pass-by-value https://stackoverflow.com/a/40523/2022162
I was asked to check calculation time depending on number of threads working on the problem. Therefore I had written a program that calculates integral using Monte Carlo method. I am dividing the range for number of threads. After that I stats threads, which calculate their part, and finally sum partial results to get general one.
The problem is that time of calculation increases with number of threads instead of decreasing (i7 processor, Windows 7)
A few people working on it, and we do not know why is that. I hope someone will give me an advice.
I attach code:
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
public class Runner {
private static final int MAXT = 10; // maksymalna ilość wątków
static PrintWriter outM;
static PrintWriter outMTime;
public static void main(String[] args){
double xp = 2;
double xk = 3;
filesOp();
// Wypisywanie kolumn tabeli
for(int threadNumber=1; threadNumber<=MAXT; threadNumber++){
outM.print("\t"+ threadNumber);
outMTime.print("\t"+ threadNumber);
}
double time1;
double time2;
//double startTime=System.currentTimeMillis(); // Przed wystartowaniem programu
for(int n=10000; n<=10000000; n=n*10){
System.out.println("Licze dla: " + n + " punktow.");
outM.print("\n"+n);
outMTime.print("\n"+n);
for(int threadNumber=1; threadNumber<=MAXT; threadNumber++){
outM.print("\t");
outMTime.print("\t");
time1=System.nanoTime();
multiThread(xp, xk, n, threadNumber);
time2=System.nanoTime();
outMTime.print((time2-time1)/1000000);
// czas pracy dla danej liczby wątków
}
}
outM.close();
outMTime.close();
}
public static void multiThread(double xp, double xk, int n, int threadNumber){
// Funkcja licząca całkę wielowątkowo.
// Całka do policzenia jest dzielona pomiędzy wątki
ArrayList<Thread> threadList = new ArrayList<Thread>();
ConcurrentLinkedQueue<Double> results = new ConcurrentLinkedQueue<Double>();
for(int i=0; i<threadNumber; i++){
MonteCarlo mc = new MonteCarlo( xp+(i*((xk-xp)/threadNumber)), xp+((i+1)*((xk-xp)/threadNumber)), (int)(n/threadNumber), results);
Thread t = new Thread(mc);
threadList.add(t);
t.start();
}
//for(int j=0; j<threadNumber; j++){ // pętla czeka na zakończenie wątków
for(Thread t : threadList){
try {
//while(t.isAlive()){}
//threadList.get(j).join();
t.join();
} catch (Exception e) {
e.printStackTrace();
}
}
double wynik = 0;
//for(int k=0; k<results.size(); k++){
for(double r: results){
//wynik = wynik + results.remove();
wynik= wynik + r;
}
outM.print(wynik);
}
public static void filesOp(){
File fileTemp;
fileTemp = new File("wyniki.txt");
if (fileTemp.exists()) fileTemp.delete();
fileTemp = new File("pomiary.txt");
if (fileTemp.exists()) fileTemp.delete();
try {
outM = new PrintWriter(new FileWriter("wyniki.txt", true));
outMTime = new PrintWriter(new FileWriter("pomiary.txt", true));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MonteCarlo implements Runnable{
double xp;
double xk;
long n;
ConcurrentLinkedQueue<Double> results;
MonteCarlo(double xp, double xk, long n, ConcurrentLinkedQueue<Double> results){
this.xp=xp;
this.xk=xk;
this.n=n;
this.results=results;
}
//funkcja dla ktorej obliczamy calke
private static double func(double x) {
return x*x+3;
}
private static double funcIn(double x, double y) {
if (( y > 0) && (y <= func(x)))
return 1;
else if (( y > 0) && (y <= func(x)))
return -1;
return 0;
}
//random number from a to b
private static double randomPoint(double a, double b) {
return a + Math.random() * (b-a);
}
public void run(){
double yp, yk, calka;
int pointsIn;
yp = 0;
yk = Math.ceil(Math.max(func(xp), func(xk)));
pointsIn = 0;
for (long i=0; i<n; i++) {
pointsIn += funcIn(randomPoint(xp, xk), randomPoint(yp, yk));
}
calka = (pointsIn / (double)n) * ((xk-xp) * (yk-yp));
results.add(calka);
}
}
And the example of results:
1 2 3 4 5 6 7 8 9 10
10000 6.185818 2.821405 3.721287 3.470309 4.068365 3.604195 4.323075 4.192455 6.159694 4.239105
100000 10.994522 15.874134 34.992323 40.851124 36.199631 49.54579 45.122417 61.427132 55.845435 60.7661
1000000 108.653008 274.443662 340.274574 407.054352 437.455361 469.853467 496.849012 584.519687 571.09329 594.152023
10000000 1066.059033 2877.947652 3600.551966 4175.707089 4488.434247 5081.572093 5501.217804 6374.335759 6128.274553 6339.043475
The problem most likely lies in
private static double randomPoint(double a, double b) {
return a + Math.random() * (b-a);
}
Math.random() performs poorly under heavy contention. If you are using java 7 or later, try this instead:
private static double randomPoint(double a, double b) {
return ThreadLocalRandom.current().nextDouble(a, b);
}
Using static funtions frequently is one of the pitfalls in Multithreading.
A more general answer can be found in this post already.
I have an arraylist of points which are drawn onto a canvas. I have made a method (drawLine) which draws a path/line from one point to another according to the points the user clicks on.
The order in which the points are clicked are put into an arraylist called userPath.
The drawLine method then captures the last two values of userPath and stores them in another arraylist called realPath, and draws a line between these two points and can be seen below.
//this class draws a line
public void drawLine(float x, float y)
{
mPath.reset();
if (userPath.size()>=2);
{
realPath.add(userPath.get(userPath.size()-1));
realPath.add(userPath.get(userPath.size()-2));
}
// start point
Point p = realPath.get(mLastPointIndex);
mPath.moveTo(p.x, p.y);
// end point
p = realPath.get(mLastPointIndex + 1);
//this goes through every point in realPath array list
mPath.lineTo(p.x, p.y);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
++mLastPointIndex;
isPathStarted = false;
}
When I call the method (drawLine(x,y)) however, it throws an error.
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
// this will draw the path
//mContext = this.mContext;
float Cox = event.getX();
float Coy = event.getY();
double CoX = (double) Cox;
double CoY = (double) Coy;
//the euclid method only accepts double numbers therefore the coordinates of the
//points the user is clicking on need to be converted from float to double
Double NearestDistance = 1000.12; //this is hardcoded for the sake of declaring the variable.
Point NearestPoint = null;
for (int i = 0; i < mPoints.size(); i++)
{
Point current = mPoints.get(i);
double xi = current.x;
double yi = current.y;
double dis = Euclid(CoX, CoY, xi, yi);
if (dis < NearestDistance)
{
NearestPoint = current;
NearestDistance = dis;
}
}
String text = "the closest point to where you clicked is: " + NearestPoint + " and the coordinates are: " + NearestPoint.x + ", "+ NearestPoint.y;
Toast.makeText(mContext, text, LENGTH_SHORT).show();
if (userPath.contains(NearestPoint))
{
String pickPoint = "Pick another point";
Toast.makeText(mContext, pickPoint, LENGTH_SHORT).show();
}
else
{
userPath.add(NearestPoint);
Toast.makeText(mContext, userPath + "", LENGTH_SHORT).show();
drawLine(x,y);
//need to call the drawLine method here to draw the line between the last 2 elements in the arraylist. this throws an error!!!
}
invalidate();
break;
}
return true;
}
I am using JXmapkit in order to display a map with way points of openstreetmaps in a frame where the co-ordinates of the waypoint are stored within a database. When a location is clicked, the application will check whether the co-ordinates of the area is within the area around a waypoint, if true than an internal frame will open. The problem is that the co-ordinates of the clicked location are always returned incorrect example, the correct co-ordinates(35.9097,14.4259) are returned as (85.05012,-179.96198). I tried to add the difference but it does not work as I cannot determine the exact difference between the co-ordinates since each time I click the same location, the co-ordinates always differ. Am I missing something or am I doing something wrong?
public static ArrayList<StopBS> GetBusStopByCoordinates(float x, float y, float radius)
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try
{
ArrayList<StopBS> stops = new ArrayList<StopBS>();
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection(ConnectionString);
statement = connection.createStatement();
// Added value
// x -= 49.1401725;
// y += 194.4150295;
float x1 = x - radius;
float x2 = x + radius;
float y1 = y - radius;
float y2 = y + radius;
String command = "SELECT StopID, StopNumber, Tag, Latitude, Longitude FROM StopTable WHERE (Latitude BETWEEN %f AND %f) AND (Longitude BETWEEN %f AND %f)" ;
command = String.format(command, x1,x2,y1,y2);
resultSet = statement.executeQuery(command);
while (resultSet.next())
{
StopBS newStop = new StopBS();
newStop.StopID = resultSet.getInt("StopID");
newStop.StopNumber = resultSet.getInt("StopNumber");
newStop.Tag = resultSet.getString("Tag");
newStop.Lat = resultSet.getFloat("Latitude");
newStop.Long = resultSet.getFloat("Longitude");
stops.add(newStop);
}
return stops;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
mainMap.getMainMap().addMouseListener(new MouseInputAdapter()
{
public void mouseClicked(MouseEvent e)
{
//Get mouse click position in screen values
Point point = e.getPoint();
//get map component
JXMapViewer map = mainMap.getMainMap();
//calculate x, y for map as the point is relative to the whole screen
Rectangle bounds = getBounds();
int x = (int)(point.getX() - bounds.getX());
int y = (int)(point.getY() - bounds.getY());
//Get the lat and long from the x and y mouse position
Point2D pixelcoord1 = point;
GeoPosition mappos = map.getTileFactory().pixelToGeo(pixelcoord1, map.getZoom());
Point2D QALLA = map.getTileFactory().geoToPixel(mappos, map.getZoom());
//check in database for busstops in that area 0.0015F
ArrayList<StopBS> stops = DataAccess.GetBusStopByCoordinates((float)mappos.getLatitude(),(float)mappos.getLongitude(), 0.0015F);
}
});
}
jXMapKit1.getMainMap().convertPointToGeoPosition(pixelcoord1)