I have a little problem. I get data from more then one Beacon and I put it into an arrayList. Now I want that the nearest one should be returned.
ArrayList<Beacon> arrayList = new ArrayList<Beacon>();
String beaconName;
public void addToBeaconInfo(Beacon beacon) {
boolean beaconAlreadyInList = false;
//arrayList.add(beacon);
beaconName = "" + beacon.getId2() + "" + beacon.getId3();
//Log.i("BeaconInfo","addBeacon_beaconName: "+beaconName + " distance" + beacon.getDistance());
int i;
for(i = 0; i < arrayList.size(); i++){
Beacon tempBeacon = arrayList.get(i);
if(tempBeacon.getId2().equals(beacon.getId2())){
beaconAlreadyInList = true;
arrayList.remove(beacon);
Log.i("BeaconInfo", "addBeacon_tempBeacon: " + beacon.getId3() + " distance: " + beacon.getDistance());
break;
}
}
if(beaconAlreadyInList == false){
arrayList.add(beacon);
Log.i("arrayList","" + beacon.getDistance() + " " + beacon.getBluetoothName());
double maxDistance = beacon.getDistance();
//double a = Collections.max(maxDistance);
//Log.i("maxDistance","" + Math.max());
}
}
Beacon nearest = null;
double distance = Double.MAX_VALUE;
for (Beacon beacon: arrayList){
double maxDistance = beacon.getDistance();
if (maxDistance < distance) {
distance = maxDistance;
nearest = beacon;
}
}
Related
private void initFlightController() {
DJIAircraft aircraft = DJISimulatorApplication.getAircraftInstance();
if (aircraft == null || !aircraft.isConnected()) {
log("initFlightController: aircraft not connected");
showToast("Disconnected");
mFlightController = null;
return;
} else {
log("initFlightController: aircraft CONNECTED");
mFlightController = aircraft.getFlightController();
DJISimulator djiSimulator = mFlightController.getSimulator();
log("initFlightController: djiSimulator has started : "+djiSimulator.hasSimulatorStarted());
djiSimulator.setUpdatedSimulatorStateDataCallback(new DJISimulator.UpdatedSimulatorStateDataCallback() {
#Override
public void onSimulatorDataUpdated(final DJISimulatorStateData djiSimulatorStateData) {
log("onSimulatorDataUpdated: ");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
String yaw = String.format("%.2f", djiSimulatorStateData.getYaw());
String pitch = String.format("%.2f", djiSimulatorStateData.getPitch());
String roll = String.format("%.2f", djiSimulatorStateData.getRoll());
String positionX = String.format("%.2f", djiSimulatorStateData.getPositionX());
String positionY = String.format("%.2f", djiSimulatorStateData.getPositionY());
String positionZ = String.format("%.2f", djiSimulatorStateData.getPositionZ());
mTextView.setText("Yaw : " + yaw + ", Pitch : " + pitch + ", Roll : " + roll + "\n" + ", PosX : " + positionX +
", PosY : " + positionY +
", PosZ : " + positionZ);
}
});
}
});
}
}
I am testing the sample code given for android in Dji-Developer. Every thing goes fine but the onSimulatorDataUpdated() doesnt get called.
it even prints the log
"initFlightController: djiSimulator has started : true"
I found the solution for the problem. The code doesn't have any problem, the RC has a button at the left front area which has to be set to P mode.
I am using graphhopper and mapsforge to show the route in my android app.The route is shown in my mapView from the polyline but when I change the location of second point the new route is shown above the previous route.So I need to delete this previous route when a new route is calculated. The code is as follows:
GraphHopper localGraphHopper = new GraphHopper().forMobile();
localGraphHopper.setCHShortcuts(true, true);
localGraphHopper.load(getFolderPath());
GHRequest localGHRequest = new GHRequest(paramDouble1, paramDouble2, paramDouble3, paramDouble4);
GHRequest a = localGHRequest.setAlgorithm("dijkstrabi");
GHResponse localGHResponse = localGraphHopper.route(localGHRequest);
int i = localGHResponse.getPoints().getSize();
PointList localPointList = localGHResponse.getPoints();
Polyline localPolyline = new Polyline(createPaint(AndroidGraphicFactory.INSTANCE.createColor(Color.RED), 4, Style.STROKE), AndroidGraphicFactory.INSTANCE);
this.latLongs_track = localPolyline.getLatLongs();
for (int j = 0;; j++)
{
if (j >= i)
{
this.mapView.getLayerManager().getLayers().add(localPolyline);
LatLong localLatLong = new LatLong((paramDouble1 + paramDouble3) / 2.0D, (paramDouble2 + paramDouble4) / 2.0D);
this.mapView.getModel().mapViewPosition.setCenter(localLatLong);
return;
}
this.latLongs_track.add(new LatLong(localPointList.getLatitude(j), localPointList.getLongitude(j)));
}
Use this function:
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon ) {
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>(){
float time;
protected GHResponse doInBackground( Void... v ){
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints().
put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp ){
if (!resp.hasErrors()){
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
mapView.getLayerManager().getLayers().add(createPolyline(resp));
//mapView.redraw();
} else{
logUser("Error:" + resp.getErrors());
}
shortestPathRunning = false;
}
}.execute();
}
All source you can find at https://github.com/graphhopper/graphhopper
I have found the answer for my problem and am posting here
Polyline localPolyline;
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon )
{
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>()
{
float time;
protected GHResponse doInBackground( Void... v )
{
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints()
.put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp )
{
if (!resp.hasErrors())
{
if(localPolyline!=null){
mapView.getLayerManager().getLayers().remove(localPolyline);
}
else{
log("here");
}
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
localPolyline=createPolyline(resp);
mapView.getLayerManager().getLayers().add(localPolyline);
} else
{
logUser("Error:" + resp.getErrors());
}
}
}.execute();
}
Thanks to everybody.
I'm coding a method that solve various kind of equation. Now I want that the method receives a String equation that could be in the forms:
ax^2+bx+c=0
or
*ax^2+c=0*
or
bx+c=0
etc. and the order shouldn't matter.
My problem is: How could I parse the equation according the "x" grade?
The eq could contains more values of the same grade for example 2x^2+4x^2+3x+8=2 (max grade x^3).
My method should assign the a value to double a[] if on the left or on the right of a there is x^2, double b[], if on the left or on the right there is x, and double c[] if there isn't any x variable near the value (and should change the value sign if the therms is after the =).
Convert a String number in a double is simple but I don't know how I could disassemble the input String according the x grade as described.
Tested for -2x + 3x^2 - 2 + 3x = 3 - 2x^2
public Double[] parseEquation(String equation)
{
Log.d(TAG, "equation: " + equation);
// Remove all white spaces
equation = equation.replaceAll("[ ]", "");
// Get the left and right sides of =
String[] sides = equation.split("[=]"); // should be of size 2
boolean leftNegative = false;
boolean rightNegative = false;
if (sides.length != 2)
{
// There is no = or more than one = signs.
}
else
{
// if sides i starts with + remove the +
// if - we remove and put it back later
for (int i = 0; i < 2; i++)
{
if (sides[i].charAt(0) == '+')
{
sides[i] = sides[i].substring(1);
}
}
if (sides[0].charAt(0) == '-')
{
leftNegative = true;
sides[0] = sides[0].substring(1);
}
if (sides[1].charAt(0) == '-')
{
rightNegative = true;
sides[1] = sides[1].substring(1);
}
}
Log.d(TAG, "left side:" + sides[0] + " right side: " + sides[1]);
// Terms without signs need to find out later
String[] leftTerms = sides[0].split("[+-]");
String[] rightTerms = sides[1].split("[+-]");
int length = leftTerms[0].length();
if (leftNegative)
{
leftTerms[0] = "-" + leftTerms[0];
}
// put in the minus sign for the rest of the terms
for (int i = 1; i < leftTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[0].charAt(length));
if (sides[0].charAt(length) == '-')
{
leftTerms[i] = "-" + leftTerms[i];
length += leftTerms[i].length();
}
else
{
length += leftTerms[i].length() + 1;
}
}
length = rightTerms[0].length();
if (rightNegative)
{
rightTerms[0] = "-" + rightTerms[0];
}
for (int i = 1; i < rightTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[1].charAt(length));
if (sides[1].charAt(length) == '-')
{
rightTerms[i] = "-" + rightTerms[i];
length += rightTerms[i].length();
}
else
{
length += rightTerms[i].length() + 1;
}
}
// Now we put all the factors and powers in a list
List<ContentValues> leftLists = new ArrayList<ContentValues>();
// left side
for (int i = 0; i < leftTerms.length; i++)
{
Log.d(TAG, "leftTerm: " + leftTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = leftTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no x mean a constant term
contentValues.put("factor", leftTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = leftTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = leftTerms[i].substring(indexOfX + 2).trim();
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
leftLists.add(contentValues);
}
List<ContentValues> rightLists = new ArrayList<ContentValues>();
for (int i = 0; i < rightTerms.length; i++)
{
Log.d(TAG, "rightTerm: " + rightTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = rightTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no hat mean a constant term
contentValues.put("factor", rightTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = rightTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = rightTerms[i].substring(indexOfX + 2).trim();
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
rightLists.add(contentValues);
}
// Now add the factors with same powers.
// Suppose we solve for cubic here the end result will be
// 4 terms constant, x, x^2 and x^3
// Declare a double array of dim 4 the first will hold constant
// the second the x factor etc...
// You can allow arbitrary power by looping through the lists and get the max power
Double[] result = new Double[]{0.0, 0.0, 0.0, 0.0};
for (ContentValues c : leftLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] += c.getAsDouble("factor");
break;
case 1:
result[1] += c.getAsDouble("factor");
break;
case 2:
result[2] += c.getAsDouble("factor");
break;
case 3:
result[3] += c.getAsDouble("factor");
break;
}
}
for (ContentValues c : rightLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] -= c.getAsDouble("factor");
break;
case 1:
result[1] -= c.getAsDouble("factor");
break;
case 2:
result[2] -= c.getAsDouble("factor");
break;
case 3:
result[3] -= c.getAsDouble("factor");
break;
}
}
Log.d(TAG, "constant term = " + result[0] + ", x^1 = " + result[1]
+ ", x^2 = " + result[2] + ", x^3 = " + result[3]);
return result;
}
If you weren't limited by Android, I'd suggest using a lexer and parser. These are code generators, so they can work anywhere the base language works, but they tend to produce bloated code. Android might not appreciate that.
I use the following code to convert elements from ArrayList to string:
public static List<Location> GPSLocalLocations = new ArrayList<Location>(1);
String mystr = "";
for (int i=0; i<GPSService.GPSLocalLocations.size(); i++)
{
mystr += "\n" + GPSService.GPSLocalLocations.get(i).toString();
}
Changed my code to the following:
for (int i=0; i<GPSService.GPSLocalLocations.size(); i++)
{
gpslog.append("\n").append(GPSService.GPSLocalLocations.get(i).toString());
}
It causes less GC Free messages :). My mistake, application didn't hang because of that... I think because I ran a my ASyncTask multiple times...
But still iterating ArrayList of more than 1000 elements takes some time [about 10 seconds]. Is that ok?
I'd recommend to use StringBuilder.
From here http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/location/Location.java#Location.toString%28%29 :
#Override public String [More ...] toString() {
return "Location[mProvider=" + mProvider +
",mTime=" + mTime +
",mLatitude=" + mLatitude +
",mLongitude=" + mLongitude +
",mHasAltitude=" + mHasAltitude +
",mAltitude=" + mAltitude +
",mHasSpeed=" + mHasSpeed +
",mSpeed=" + mSpeed +
",mHasBearing=" + mHasBearing +
",mBearing=" + mBearing +
",mHasAccuracy=" + mHasAccuracy +
",mAccuracy=" + mAccuracy +
",mExtras=" + mExtras + "]";
}
I'd recommend write it yourself in following way:
public static List<Location> GPSLocalLocations = new ArrayList<Location>(1);
StringBuilder gpslog = new StringBuilder();
for (int i=0; i<GPSService.GPSLocalLocations.size(); i++)
{
Location location = GPSService.GPSLocalLocations.get(i);
gpslog.append("\n")
.append("Location[Provider=").append(location.getProvider(())())
.append(",Time=").append(location.getTime())
.append(",Latitude=").append(location.getLatitude())
.append(",Longitude=").append(location.getLongitude())
.append(",HasAltitude=").append(location.getHasAltitude())
.append(",Altitude=").append(location.getAltitude())
.append(",HasSpeed=").append(location.getHasSpeed())
.append(",Speed=").append(location.getSpeed())
.append(",HasBearing=").append(location.getHasBearing())
.append(",Bearing=").append(location.getBearing())
.append(",HasAccuracy=").append(location.getHasAccuracy())
.append(",Accuracy=").append(location.getAccuracy())
.append(",Extras=").append(location.getExtras()).append("]");
}
I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}