android mathematical calculations in eclipse java - android

Can anybody tell me why the result of the following expression is -4.91679930495
9.81*Math.cos(phi)/Math.sin(phi)
if phi = 90°?
In particular, I want to display the value of acceleration.
tvText2.setText("acceleration: " + String.valueOf(9.81*Math.cos(phi)/Math.sin(phi)) + " m/s²");

Acording to docs http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#cos(double):
The paremeter of those methods is in radians.
you will need to call Math.toRadians that receives an angle in degrees. http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#toRadians(double)

Convert phi to Radian before calculating acceleration:
double phiInRad = Math.toRadians(phi);
tvText2.setText("acceleration: " + String.valueOf(9.81*Math.cos(phiInRad)/Math.sin(phiInRad)) + " m/s²");
or in one line
tvText2.setText("acceleration: " + String.valueOf(9.81*Math.cos(Math.toRadians(phi))/Math.sin(Math.toRadians(phi))) + " m/s²");

Related

Decimal point issue in displaying digits

I have to display digit in two decimal points.
Let say value 0 should display as 0.00 and value 2.3 shoule display as 2.30.
To achive this I have done something like below :
Log.e(">>> percent ", ">> " + data.percent)
percent = String.format("%.2f", percent).toDouble()
Log.e(">>> percent ", ">> " + percent)
But the result you will notice is as below :
2021-04-15 11:55:54.580 10061-15047/com.dev E/>>> percent: >> 0
2021-04-15 11:55:54.580 10061-15047/com.dev E/>>> percent: >> 0.0
It should be 0.00 instead of 0.0
What might be the issue?
Please guide. Thanks.
Double type does not have information about how to display.
So, do not use toDouble() method to the string.
Also, add 0 to the format string to denote the zero padding.
Log.e(">>> percent ", ">> " + data.percent)
val percentStr: String = String.format("%.02f", data.percent)
Log.e(">>> percent ", ">> " + percentStr)
You can use DecimalFormat https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
val df = DecimalFormat("0.00")
df.format(percent)
just change
String.format("%.2f", percent).toDouble()
to
String.format("%.02f", data.percent)

How can I use the Magnetometer from this Sensor API?

I'm trying to get use the magnetometer from this Sensor API but I'm not sure if I'm doing so correctly.
I copied and edited the example code from the their site into my test site;
let sensor = new Magnetometer();
sensor.start();
sensor.onreading = () => {
console.log("Magnetic field along the X-axis " + sensor.x);
console.log("Magnetic field along the Y-axis " + sensor.y);
console.log("Magnetic field along the Z-axis " + sensor.z);
document.getElementById("x").innerHTML = "X = " + sensor.x;
document.getElementById("y").innerHTML = "Y = " + sensor.y;
document.getElementById("z").innerHTML = "Z = " + sensor.z;
};
sensor.onerror = event => console.log(event.error.name, event.error.message);
But when I load the page it doesn't give me any readings. Checking the site on my laptop brings back this error message;
Uncaught ReferenceError: Magnetometer is not defined
at magnetometer.js:1
Any insight into this would be greatly appreciated.
I found the answer. After looking around I found that you need to go to chrome://flags/#enable-generic-sensor-extra-classes and enable Generic Sensor Extra Classes.
I'm not sure why this is the case but I am now getting the readings I was after.

How can I round numbers (2 decimal) parseXml get(field) in Android

TextView.setText(XMLdata.get("XMLField") + " mm");
input values that are expressed in an abbreviated way:
10,5858555966668 (with comma)
Which I would like to convert into:
10,58
if your XMLdata.get("XMLField") value is float u can do the following code
String finalValue = String.format(
"%.2f", XMLdata.get("XMLField"));
TextView.setText(finalValue + " mm");
if your XMLdata.get("XMLField") is String convert it into float do the above method.
TextView.setText((Math.floor(MathXMLdata.get("XMLField") * 100.0) / 100.0).toString() + " mm");
This converts 10,5858555966668 to 1058,58555966668, rounds it to 1058 and converts it back to 10,58.
Note: Math.floor always rounds down (cuts off all missing fractional numbers). If you intend to round to the closest value, use Math.round.
Thank you, thank you very much rmkrishna and Faro ((= I do it with
TextView.setText(String.format("%.2f",Double.parseDouble(XMLData.get("Son7GunlukSagis").replace(",", ".")))+ " mm");

How can I get exact GPS location with AIR Geolocation API?

How can I get the exact Latitude and Longitude? I only get whole numbers. From my understanding, in order to get down to the meter I need to get down to 5 decimal places. I have tried the horizontal and vertical accuracy but they don't match my phones GPS reading.
How can I get an exact GPS reading with Geolocation API, Down to the meter?
here is my code
var my_geo:Geolocation = new Geolocation();
my_geo.setRequestedUpdateInterval(2000);
my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);
function onGeoUpdate(e:GeolocationEvent):void
{
gpsLat1 = (e.latitude);
gpsLon1 = (e.longitude);
gpsHeading = (e.heading);
gpsHorAcc = (e.horizontalAccuracy);
gpsVerAcc = (e.verticalAccuracy);
gpsCheck = 2;
my_txt.text = "My Latitude is "+ gpsLat1 + " and my Longitude is "+ gpsLon1 + " Bearing is " + gpsHeading+ " HorAcc "+ gpsHorAcc+ " VertAcc "+gpsVerAcc;
}
Make sure your variables (gpsLat1, gpsLon1, gpsHeading, etc.) are of type Number and not a uint or int. Unsigned Integers and Integers only allow for whole numbers, whereas Number is the equivalent of float in most other languages (and allows for incredibly larger values, as well). If you save a decimal to an integer, it is rounded off/floored (I can't remember which), which sounds exactly like the problem you are having.
Alternatively, the API is restricted by the hardware you are testing on. If the hardware only returns a certain value for GPS coordinates, AIR cannot be any more precise. Odds are this is not the issue since a whole lat long point can be miles and miles in distance, meaning any device with that inaccurate of a GPS chip is absolutely useless.
Try this:
function onGeoUpdate(e:GeolocationEvent):void
{
gpsLat1 = (e.latitude.toString());
gpsLon1 = (e.longitude.toString());
gpsHeading = (e.heading.toString());
gpsHorAcc = (e.horizontalAccuracy.toString());
gpsVerAcc = (e.verticalAccuracy.toString());
gpsCheck = 2;
my_txt.text = "My Latitude is "+ gpsLat1 + " and my Longitude is "+ gpsLon1 + " Bearing is " + gpsHeading+ " HorAcc "+ gpsHorAcc+ " VertAcc "+gpsVerAcc;
}

Attempting to remove an object off screen moves all the objects in play?! - Android. Please Help!

I am building an android game where objects randomly come in from either side of the screen towards a sprite in the middle of the screen. When one passes the tripwire on the central sprite it is dealt with by my collision detection which sets the enemy objects co-ordinates to somewhere off the screen, thats desired but as this happens in my updatePhysics() method when we loop back to the doDraw() method the canvas has redrawn to an empty state (ie. without any enemy objects on it). Any objects that were on screen and not colliding with the sprite are erased too and new ones regenerated. Why is it removing all the enemy objects rather than just updating the position of the ones left in play at that point???
I will include my code to make this simpler to understand. This is the collision detection part of my updatePhysics():
// COLLISION DETECTION
int n = 0,haveHidden = 0; //haveHidden is number of objects that are hidden in this current pass of CD
while(n < mCurrentDistractionsOnScreen){
switch(DistractionsArray[n].dGeneralDirection){
case LEFT_ORIGIN:
// If the X co-ordinate is past the edge of the performer sprite
if((DistractionsArray[n].ObjmX2 > LEFT_TRIPWIRE) && (DistractionsArray[n].ObjmX2 < RIGHT_TRIPWIRE))
{
mConcentration -= DistractionsArray[n].dDamageToInflict;
Log.w(this.getClass().getName(), "Object: " + n + "LEFT Damage: " + DistractionsArray[n].dDamageToInflict + " leaves " + mConcentration);
DistractionsArray[n].hideDistraction();
haveHidden++;
}
break;
case RIGHT_ORIGIN:
// If the X co-ordinate is past the edge of the performer sprite
if((DistractionsArray[n].ObjmX > LEFT_TRIPWIRE) && (DistractionsArray[n].ObjmX < RIGHT_TRIPWIRE))
{
mConcentration -= DistractionsArray[n].dDamageToInflict;
Log.w(this.getClass().getName(), "Object: " + n + "RIGHT Damage: " + DistractionsArray[n].dDamageToInflict + " leaves " + mConcentration);
DistractionsArray[n].hideDistraction();
haveHidden++;
}
break;
}
n++;
mCurrentDistractionsOnScreen -= haveHidden;
}
This is the hideDistraction() method that is a method defined in the DistractionObjects inner class in this thread (DistractionsArray consists of these objects):
public void hideDistraction(){
// Set attributes to default
this.dName = "Default";
this.dVelocity = 0;
this.dMaxPoints = 10;
this.dDamageToInflict = 0;
this.dOrigin = 100;
this.dGestureRequired = "";
// Can be reused again
this.isUseable = true;
Log.w(getClass().getName(), "HIDING FROM: " + this.ObjmX + " " + this.ObjmY + " " + this.ObjmX2 + " " + this.ObjmY2 + " ");
// Position it off-screen
this.ObjmX = -150;
this.ObjmX2 = -150 + this.dDistractionObjectSprite1.getIntrinsicWidth();
this.ObjmY = -150;
this.ObjmY2 = -150 + this.dDistractionObjectSprite1.getIntrinsicHeight();
Log.w(getClass().getName(), "HIDING TO: " + this.ObjmX + " " + this.ObjmY + " " + this.ObjmX2 + " " + this.ObjmY2 + " ");
}
And the doDraw method starts by canvas.save() and at the end does a canvas.restore. To render my objects at their new position it does this:
// For each object in play, draw its new co-ordinates on the canvas
int n = 0;
while(n < mCurrentDistractionsOnScreen){
DistractionsArray[n].dDistractionObjectSprite1.setBounds((int)DistractionsArray[n].ObjmX,
(int)DistractionsArray[n].ObjmY,
(int)DistractionsArray[n].ObjmX2,
(int)DistractionsArray[n].ObjmY2);
DistractionsArray[n].dDistractionObjectSprite1.draw(canvas);
n++;
}
I am literally devoid of any ideas now after trying so many different fixes, even attempted to serialize the position of those other enemy objects on screen in an integer array that is rebuilt in the physics method but nothing!!
To summarise, I need a way of hiding the enemy object off-screen like in hideDistraction() when it passes the tripwire, but I want all the other objects to still continue on course as they are without being moved off screen and re-rendered from scratch.
If you need more details please ask....and if you can, pleaseeee help!
Many thanks
Greenhouse,
You are controlling your loop using the mCurrentDistractionsOnScreen, but you are also resetting the mCurrentDistractionsOnScreen inside of the loop. You likely don't want to be doing this. The exact reason it is removing everything is likely very difficult to pin down (i'm not surprised you couldn't figure it out!). Try re-factoring that main while loop to something like this:
for (Distraction distraction: DistractionsArray) {
switch(distraction.dGeneralDirection) {
case LEFT_ORIGIN:
// Your code goes here ...
break;
case RIGHT_ORIGIN:
// Your code goes here ...
break;
}
}
When pasting your code, remove all references to DistractionsArray[n] and replace them with distraction
EDIT:
If this helps you, then please consider 1) accepting more answers on your questions and 2) Not putting stuff like 'please help' in your titles. It's a site geared towards help, we know what you are looking for ;)
Your hideDistraction() and doDraw code is likely fine.

Categories

Resources