Add Toast in public class corresponding to any event - android

There all, i'm a newbie in android programming and i've a school task to analysis some project. So, i choose a Guitar Tuner project from github called pTune (link: here).
I've read the code and analyze it, from what i read and see there are a needle with an arc meter to see if the input sound (guitar voice) was fit.
In that project i want to display Toast if the tuning process are fit when the dial in 90 degree. So, i've add this Toast but its not displayed..
if (relativeFrequency == targetFrequency){
Toast.makeText(PTuneActivity.this, "FIT", Toast.LENGTH_SHORT).show();
}
That code placed in updateDisplay class, i've placed it in other class but still not work as i want.
public void updateDisplay(float frequency) {
// Calculate difference between target and measured frequency,
// given that the measured frequency can be a factor of target.
float difference = 0;
if (frequency > targetFrequency) {
int divisions = (int) (frequency / targetFrequency);
float modified = targetFrequency * (float) divisions;
if (frequency - modified > targetFrequency / 2) {
modified += targetFrequency;
divisions++;
}
difference = (frequency - modified) / (float) divisions;
} else {
// If target is greater than measured, just use difference.
difference = frequency - targetFrequency;
}
float relativeFrequency = targetFrequency + difference;
// Update TextView
if (relativeFrequency < 1000f)
t.setText(String.format("%.1f Hz", relativeFrequency));
else
t.setText(String.format("%.2f kHz", relativeFrequency/1000));
//My code
if (relativeFrequency == targetFrequency){
Toast.makeText(PTuneActivity.this, "FIT", Toast.LENGTH_SHORT).show();
}
// Update DialView
float value = difference / (targetFrequency / 2) * 90;
dial.update(value);
}
I know this is useless in real implementation but i want to learn android programming.

You're testing equality between 2 floats, one comes from an input ? It might never be exactly equal. You should add some log and an "else" statement to see if it goes inside the "if" because the Toast may not be the real problem

i've just try it by my self by digging and its worked for me, though its not good at all but i thinks ok, just add this line of code upper dial.update(value);
if (frequency >= targetFrequency) {
Toast.makeText(PTuneActivity.this, "FIT", Toast.LENGTH_SHORT).show();
}

Related

Square Root formula in Calculator

Ok I am having an issue trying to put a square root equation in a calculator. I am trying to figure out the expression builder. I know the expression builder takes the math operations of add, subtract, multiply, divide, equals and the parenthesis. What I am doing is trying to build the square root section. I have a simple Percent code to help with the square root.
In the Square root vs the Percent you see I am using binding. So here is the code for both.
On the square root is it possible to use the expression builder? I know there is no absolute formula for square root except for a number that is multipliable with itself like the number 4.
Sqrt(4) = 2
binding.btnSqrt.setOnClickListener {
var square = (tv_equation.text.toString().toDouble() / 2)
binding.tvResult.text = square.toString()
}
So in the event you a non square equation
sqrt(23) = 4.79
How would I simulate that as one function within the button. Can I use expression or would I need to use Kotlin.math
So between the two I divide by 100 on the percent. It works great.
binding.btnPercent.setOnClickListener {
var percentage = (tv_equation.text.toString().toDouble() / 100)
binding.tvResult.text = percentage.toString()
}
All my other buttons work fine and so I am just working on the square root before I can release this to google play.
You would need to use some form of a square root function.
AS you mentioned in your question Kotlin Sqrt Function is a very suitable choice
binding.btnSqrt.setOnClickListener {
if(!tv_equation.text.isNullOrEmpty){
var number = tv_equation.text.toString().toDouble()
binding.tvResult.text = sqrt(number).toString()
}
You can create a sqrt function using the Quake's first inverse square root.
Quake's first inverse square root.
Pseudo Code:
float InvSqrt(float x){
float xhalf = 0.5f * x;
int i = *(int*)&x; // store floating-point bits in integer
i = 0x5f3759df - (i >> 1); // initial guess for Newton's method
x = *(float*)&i; // convert new bits into float
x = x*(1.5f - xhalf*x*x); // One round of Newton's method
return x;
}
So the answer i want to add is a little more suitable with the previous answer. Maybe this will help some people in the future. This solution will also limit the decimal space to 4 decimals.
binding.btnSqrt.setOnClickListener{
val df = DecimalFormat("#.####")
if(!tv_equation.text.isNullOrEmpty())
{
val number = tv_equation.text.toString().toDouble()
binding.tvResult.text = df.format(sqrt(number))
}
}
you can adjust the val df = DecimalFormat("#.####") where the # to as many decimals as you would want.

Zoom in/out limits on AS3 for iOS programming

I'm having a trouble with my code. I've made the basic zoom with AS3, using the two fingers to zoom it. But I have a trouble;
I need the zoom in stop in 2 for example (the normal size is 1), and then, I need to zoom out max to 1. Here is my code, but if I zoom fast, the zoom goes more than 2.
I need to limit the zoom, between 1, and 2.
Multitouch.inputMode = MultitouchInputMode.GESTURE;
escenario.addEventListener(TransformGestureEvent.GESTURE_PAN, fl_PanHandler);
stage.addEventListener(TransformGestureEvent.GESTURE_ZOOM, fl_ZoomHandler);
function fl_PanHandler(event:TransformGestureEvent):void
{
event.currentTarget.x += event.offsetX;
event.currentTarget.y += event.offsetY;
}
function fl_ZoomHandler(event:TransformGestureEvent):void
{
if (event.scaleX && event.scaleY >= 1 && escenario.scaleX && escenario.scaleY <= 2)
{
escenario.scaleX *= event.scaleX;
escenario.scaleY *= event.scaleY;
trace(escenario.scaleX);
}
}
Since you're doing a times/equals (*=) your value can easily go above the threshold of 2 in your if statement since you are multiplying that value after the if statement. You could just do this:
function fl_ZoomHandler(event:TransformGestureEvent):void {
var scale:Number = escenario.scaleX * event.scaleX; //the proposed new scale amount
//you set both the scaleX and scaleY in one like below:
escenario.scaleY = escenario.scaleX = Math.min(Math.max(1,scale), 2);
//^^^^ inside the line above,
//Math.max(1, scale) will return whatever is bigger, 1 or the proposed new scale.
//Then Math.min(..., 2) will then take whatever is smaller, 2 or the result of the previous Math.max
trace(escenario.scaleX);
}

How to optimize my Android flash game?

I have a game that I converted to my Android phone. I tried both renders, and found out that CPU mode is a better option than GPU for my type of game. In GPU mode, the game has a lot of lag and the graphics are not sharp as it is in CPU mode. The purpose of the game is to kill enemies coming from the top of the screen before they hit the bottom. When the game starts, it's not laggy at all, but then it starts to lag when there are a few enemies on the screen and they start coming down faster. This is the code of spawning the enemies:
function makeEnemies():void
{
var chance:Number = Math.floor(Math.random() * 150);
if (chance <= level && enemies.length < 4)
{
tempEnemy = new Enemy();
tempEnemy.x = Math.round(Math.random() * 480);
tempEnemy.cacheAsBitmap = true;
addChild(tempEnemy);
tempEnemy.scaleX = 1.5;
tempEnemy.scaleY = 1.5;
enemies.push(tempEnemy);
tempEnemy.speed = enemyBaseSpeed + ((level - 1) * speedLevelInc);
if (tempEnemy.speed > MAX_SPEED)
{
tempEnemy.speed = MAX_SPEED;
}
}
}
function moveEnemies():void
{
var tempEnemy:MovieClip;
for (var i:int =enemies.length-1; i>=0; i--)
{
tempEnemy = enemies[i];
if (tempEnemy.dead)
{
score++;
score++;
roachLevel.score_txt.text = String(score);
enemies.splice(i,1);
}
else
{
tempEnemy.rotation += (Math.round(Math.random()*.4));
tempEnemy.x -= (Math.sin((Math.PI/180)*tempEnemy.rotation))*tempEnemy.speed;
tempEnemy.y += (Math.cos((Math.PI/180)*tempEnemy.rotation))*tempEnemy.speed;
if (tempEnemy.x < 10)
{
tempEnemy.x = 11;
}
if (tempEnemy.x > stage.stageWidth - offset)
{
tempEnemy.x = stage.stageWidth - offset;
}
if (tempEnemy.y > stage.stageHeight)
{
removeEnemy(i);
lives--;
roachLevel.lives_txt.text = String(lives);
}
}
}
}
This code is always looped to spawn multiple enemies. All my images have been converted to bitmaps. Is there any other way for me to make my game with no lag? The faster they get, the more lag they have and the user can't kill them anymore. Please help!
There are certain optimizations you can make (whether or not it's enough I can't tell):
you don't need cacheAsBitmap if you've converted everything to bitmaps, so comment this out
don't set scale! this will definitely slow things down. Since scale always seems to be 1.5, just resize your graphics
don't set tempEnemy.rotation on each iteration, if possible. Can you make tempEnemy a MovieClip that "pre-rotates" each frame in the timeline? This will be way more efficient for Flash. The rotation can be set as a Number property in the MovieClip class if you still need it for calculating tempEnemy.x and y.
(There are several minor things you can optimize, like setting var K = (Math.PI/180)*tempEnemy.rotation) in the enemies loop-- but this won't gain you a lot)

using LinearAcceleration and time passed to get distance traveled - android [duplicate]

This question already has answers here:
How to use Accelerometer to measure distance for Android Application Development
(2 answers)
Closed 9 years ago.
I know i am opening up a can of worms with trying to get the linear motion of a device using the accelerometer, but please just humor me.
I am trying to figure out the right formula to take the Sensor.TYPE_LINEAR_ACCELEROMETER (which i believe is normal accelerometer data minus gravity) and essentially say "this much time has passed and the i have accelerated x amount since last time, so i have traveled d amount.
should be something like distanceTraveledOnX = linearAccerationOfX * TimePassed;
easy enough in the real world right? if i have been going 1 mile a minute for 10minutes then i have traveled 10 miles.. speed * time = distance
problem is im not sure what the linearAcceleration is using for unit of measure. I know my timePassed is in NanoSeconds as i am saying (in my onSensorChanged)
currentTime = System.nanoTime();//var of type (double)
timePassed = currentTime - lastTime;
lastTime = currentTime;
can someone please help me figure out the formula for translating the linearAcceleration value to a nanoSecond measurement..
thanks
EDIT
here is the code im currently using but im always getting 0 :
public void onSensorChanged(SensorEvent evt) {
if (type == Sensor.TYPE_LINEAR_ACCELERATION) {
newTime = System.currentTimeMillis()/1000;
float oldVelocity = lastTime1-lastTime0;
float newVelocity = newTime- lastTime1;
if(oldVelocity<1)oldVelocity =1;
newX = lastX1 + ((lastX1 - lastX0)/oldVelocity)*newVelocity +(evt.values[0]/2)*(newVelocity*newVelocity);
lastX0 = lastX1;
lastX1 = newX;
lastTime0 = lastTime1;
lastTime1 = newTime;
Log.v("SENSOR MAN LINEAR", "new X:"+newX);
}
}
This stuff is high school physics, and if you don't know the difference between acceleration and velocity, you'll need to review it before you have any hope here.
I can tell you this much: the linear acceleration readings from a cell phone or tablet aren't remotely precise or accurate enough to do what you want without constant correction (via gps or other methods). There is an entire field of study trying to solve this problem. I've attended conferences on it.
That said, you also need to take into account that the orientation of your device will also change, unless this is some sort of special application, e.g. the device is trapped onto a sled which can only move in one direction.
Let's assume that case, and assume that the device is strapped to your sled with the right side of the device (+X axis) aligned in the direction of travel. Let's also assume that the initial position of the sled is known (call it X0) when the program starts, and that the initial velocity is zero.
Your code looks approximately like this:
double x0; // previous position, meters
double x; // current position
double v0; // previous velocity, meters/second
double v; // current velocity
long t0; // previous time, nanoseconds
long t; // current time
public void onStart() {
x0 = getInitialPosition();
x = x0;
v0 = 0;
v = v;
t0 = System.getCurrentTime() * 1000000;
// Enable sensors; left as an exercise for the reader
}
public void onSensorChanged(SensorEvent event) {
// Assume linear acceleration is the only active sensor
double accel = event.values[0]; // X axis is our axis of acceleration
t = event.timestamp;
double dt = (t - t0) * .000001;
v = v0 + accel * dt;
x = x0 + v * dt;
t0 = t;
v0 = v;
x0 = x;
}
This is by no means a complete solution. Doing this right involves differential equations which I'm not equipped to explain here (translation: I've forgotten everything I learned in college). However, if your acceleration value is accurate enough, and your time slice is short enough, this is viable.
If you need to solve this in more than one direction, it's only slightly more complicated provided that the device never changes orientation. If it does, then you also need to capture the rotation sensor and learn about quaternions and rotation matrices.
And even if you do everything right, errors will still accumulate, so now you want some sort of correction factor based on GPS, known geometry of the environment (e.g. if you're indoors and the software has a map of the building, it can make corrections when you turn a corner), and other environmental clues such as WiFi hotspots in known locations.
You might want to read up on Kalman filters at this point.
Executive summary: this is a HARD problem in the general case, and if you solve it, there's probably fame and fortune waiting for you.
Well, the correct form, known from school, is
finalXPosition = (linearAcceleration*timePassed^2)/2+ initialVelocity*timePassed+initialXPosition
finalVelocity = initialVelocity*timePassed
chaining these chunks you'll get your theoretical values.
In practice, best results are achieved by regular calibration of initialXPosition and initialVelocity through GPS.
simple example to receive calibrated horizontal acceleration in onSensorChanged:
class Integrator {
private float position = 0f;
private float velocity = 0f;
public void setGpsPosition (float gpsPosition) {
position = gpsPosition;
}
public void setGpsVelocity (float gpsVelocity) {
velocity = gpsVelocity;
}
public void onAccelerationChangeHandler(float acceleration, float timePassed) {
position += acceleration*timePassed*timePassed/2f + velocity*timePassed;
velocity += acceleration*timePassed;
}
public float getCurrentPosition() {
return position;
}
}
usage for x-acceleration:
long lastTime = 0;
public void onSensorChanged(SensorEvent evt) {
if (evt.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
long newTime = System.currentTimeMillis();
OnAccelerationChangeHandler(evt.values[0], (newTime-lastTime)/1000);
lastTime = newTime;
}
Please, note that outside a minute scale the error makes this all meaningless w/o gps correction. Understand, that if you are walking at constant speed the sensor won't give you anything at all.

Android Compass orientation on unreliable (Low pass filter)

Im creating an application where i need to position a ImageView depending on the Orientation of the device.
I use the values from a MagneticField and Accelerometer Sensors to calculate the device orientation with
SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerValues, magneticFieldValues)
SensorManager.getOrientation(rotationMatrix, values);
double degrees = Math.toDegrees(values[0]);
My problem is that the positioning of the ImageView is very sensitive to changes in the orientation. Making the imageview constantly jumping around the screen. (because the degrees change)
I read that this can be because my device is close to things that can affect the magneticfield readings. But this is not the only reason it seems.
I tried downloading some applications and found that the "3D compass" and "Compass" remains extremely steady in its readings (when setting the noise filter up), i would like the same behavior in my application.
I read that i can tweak the "noise" of my readings by adding a "Low pass filter", but i have no idea how to implement this (because of my lack of Math).
Im hoping someone can help me creating a more steady reading on my device, Where a little movement to the device wont affect the current orientation.
Right now i do a small
if (Math.abs(lastReadingDegrees - newReadingDegrees) > 1) { updatePosition() }
To filter abit of the noise. But its not working very well :)
Though I havn't used the compass on Android, the basic processing shown below (in JavaScript) will probably work for you.
It's based on the low pass filter on the accelerometer that's recommended by the Windows Phone team with modifications to suit a compass (the cyclic behavior every 360").
I assume the compass reading is in degrees, a float between 0-360, and the output should be similar.
You want to accomplish 2 things in the filter:
If the change is small, to prevent gitter, gradually turn to that direction.
If the change is big, to prevent lag, turn to that direction immediatly (and it can be canceled if you want the compass to move only in a smooth way).
For that we will have 2 constants:
The easing float that defines how smooth the movement will be (1 is no smoothing and 0 is never updating, my default is 0.5). We will call it SmoothFactorCompass.
The threshold in which the distance is big enough to turn immediatly (0 is jump always, 360 is never jumping, my default is 30). We will call it SmoothThresholdCompass.
We have one variable saved across the calls, a float called oldCompass and it is the result of the algorithm.
So the variable defenition is:
var SmoothFactorCompass = 0.5;
var SmoothThresholdCompass = 30.0;
var oldCompass = 0.0;
and the function recieves newCompass, and returns oldCompass as the result.
if (Math.abs(newCompass - oldCompass) < 180) {
if (Math.abs(newCompass - oldCompass) > SmoothThresholdCompass) {
oldCompass = newCompass;
}
else {
oldCompass = oldCompass + SmoothFactorCompass * (newCompass - oldCompass);
}
}
else {
if (360.0 - Math.abs(newCompass - oldCompass) > SmoothThresholdCompass) {
oldCompass = newCompass;
}
else {
if (oldCompass > newCompass) {
oldCompass = (oldCompass + SmoothFactorCompass * ((360 + newCompass - oldCompass) % 360) + 360) % 360;
}
else {
oldCompass = (oldCompass - SmoothFactorCompass * ((360 - newCompass + oldCompass) % 360) + 360) % 360;
}
}
}
I see that the issue was opened 5 months ago and probably isn't relevant anymore, but I'm sure other programmers might find it useful.
Oded Elyada.
This lowpass filter works for angles in radians. Use the add function for each compass reading, then call average to get the average.
public class AngleLowpassFilter {
private final int LENGTH = 10;
private float sumSin, sumCos;
private ArrayDeque<Float> queue = new ArrayDeque<Float>();
public void add(float radians){
sumSin += (float) Math.sin(radians);
sumCos += (float) Math.cos(radians);
queue.add(radians);
if(queue.size() > LENGTH){
float old = queue.poll();
sumSin -= Math.sin(old);
sumCos -= Math.cos(old);
}
}
public float average(){
int size = queue.size();
return (float) Math.atan2(sumSin / size, sumCos / size);
}
}
Use Math.toDegrees() or Math.toRadians() to convert.
Keep in mind that, for example the average of 350 and 10 is not 180. My solution:
int difference = 0;
for(int i= 1;i <numberOfAngles;i++){
difference += ( (angles[i]- angles[0] + 180 + 360 ) % 360 ) - 180;
}
averageAngle = (360 + angles[0] + ( difference / numberOfAngles ) ) % 360;
A low pass filter (LPF) blocks fast changing signals and
allows only slow changes in the signals. This means any small
sudden changes will be ignored.
The standard way to implement this in software is to take a running average
of the last N samples and report that value. Start with N as small as 3 and
keep increasing N until you find sufficient smoothed out response in your app.
Do keep in mind that the higher you make N, slower the response of the system.
See my answer to this related question: Smoothing data from a sensor
A software low pass filter is basically a modified version of that. Indeed, in that answer I even provided this link to another related question: Low pass filter software?

Categories

Resources