I am making an app using ML KIT. I am currently implementing counting while doing squats. The problem is that it counts when it goes down to a certain angle, but because it is a real-time tracking, it counts multiple times rather than once. In other words, practically when I do one squat, the counting is much more than that.
So I tried solving the problem using a timer handler. But I failed. Here is my code What should I do?
//going down
if((rightKneeAngle<=90 && leftKneeAngle<=90) || (rightHipAngle<=135 && leftHipAngle<=135)){
//Timer setting
mTimer.schedule(new CustomTimer(), 2000);
Log.d("PoseGraphic.class", "goingdown"+"rightKneeAngle : " + rightKneeAngle+ " leftKneeAngle : " + leftKneeAngle);
Log.d("PoseGraphic.class","leftHip"+leftHipAngle+"RighHip"+rightHipAngle);
Log.d("PoseGraphic.class", "cnt: " + cnt);
//going up
if((rightKneeAngle>170 && leftKneeAngle>90)|| (rightHipAngle>135 && leftHipAngle>135)){
Log.d("PoseGraphic.class", "going up"+"rightKneeAngle : " + rightKneeAngle+ " leftKneeAngle : " + leftKneeAngle);
Log.d("PoseGraphic.class","leftHip"+leftHipAngle+"RightHip"+rightHipAngle);
if(cnt==12) {
canvas.drawText("complete!", x, y, textPaint);
//ExerciseCount.cnt = 0;
cnt=0;
}
}
}
// TIMER handler class
class CustomTimer extends TimerTask
#Override
public void run() {
cnt++;
}
I cannot fully understand how you do it without seeing more code.
An suggestion would be:
Instead of +1 to the count when the pose is in squat_down state, record the entering of that state with a boolean and +1 to the count only once the user exit squat_down and enter squat_up state. Then reset the state boolean.
By doing this, you will only +1 when user finish an entire cycle from squat_down to up.
Actually, ML Kit just launched an example for squat and pushup classification and rep-counting. Here is the app you can try. If you want to classify some other poses, here is some guide and a Colab.
Related
I am making a location-based app, that has a compass which is pointing to some Long and Lat coordinates. I need to access my own coordinates, to be able to calculate the rotation my compass needs, but the problem is - my unity location service is timing out. This apps location sensitivity is 3 meters.
I created a second app, which is just showing you your Long and Lat coordinates with location sensitivity of 5 meters and it works almost instantly. Here is the code of my first project:
IEnumerator Start()
{
// First, check if user has location service enabled
if (!Input.location.isEnabledByUser)
{
ErrorHandler.ShowMessageError("Location service not enabled");
isLoopAllowed = false;
yield break;
}
// Start service before querying location
Input.location.Start(Storage.LOCATION_SENSITIVITY, Storage.LOCATION_SENSITIVITY);
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait < 1)
{
ErrorHandler.ShowMessageError("Timed out");
isLoopAllowed = false;
yield break;
}
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
ErrorHandler.ShowMessageError("Can't locate your device");
isLoopAllowed = false;
yield break;
}
else
{
// Access granted and location value could be retrieved
//print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
Storage.USER_LATITUDE = Input.location.lastData.latitude;
Storage.USER_LONGITUDE = Input.location.lastData.longitude;
Storage.LOCATION_READY = true;
}
}
Some intro into the script:
isLoopKeyAllowed variable is for stopping the loop in case of an error.
Storage class is just a class with global variables.
ErrorHandler class has a function called ShowMessageError() thats just outputting the error on the screen.
LOCATION_READY is a varible that is being used by the compass script.
and thats it. I don't know whats the problem. Maybe it is caused because the sensitivity is too high?
(EDIT): The problem is, that the Timed Out error is shown and the loop has ended.
I'm in the middle of developping a map app that enables user to send duration data that it takes him to get to another place, to the database (MySQL) , for this reason I tried to extract the double value of duration directely from url as it's showing in the method below :
#Override
public void setDouble(String result) {
String res[]=result.split(",");
Double min=Double.parseDouble(res[0])/60;
int dist=Integer.parseInt(res[1])/1000;
Duree.setText("Duration= " + (int) (min / 60) + " hr " + (int) (min % 60) + " mins");
Distance.setText("Distance= " + dist + " kilometers");
}
In this method it worked, but when I tried to do it like this :
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+latt+","+lngg+"&destinations="+lt+","+lg+"&mode=driving&language=fr-FR&avoid=tolls&key=API_KEY";
String res[]=url.split(",");
Double duration=Double.parseDouble(res[0])/60;
It showed me that it's not a valid double value, knowing that I need to send this value when I click a button showed on a popup window after marker click (So the problem of inner class is posed).
Can you help me know what is the right way to do it ,if that is possible !
Don't expect your first result-field contains the duration but make your parsing a little more intelligent. Use, by example, the org.json library (introduction on json
Following code snippet should help a little:
LOGGER.debug("---google duration in seconds = {}", jsonElement.opt("duration") == null ? 0 : jsonElement.getJSONObject("duration").get("value"));
transportInfo.setDuration(jsonElement.opt("duration") == null ? 0 : (Integer) jsonElement.getJSONObject("duration").get("value"));
And, btw, I would recommend removing your API key ASAP from your post .... Be aware this key could be used by other people.
In my android program, I have 3 functions that will be continuously repeated until the user exits the app. Currently, it is able to update a value(position) every second.
I was wondering if having lots of if else condition in one of the function will slow down the performance of my app i.e. it might take way longer than a second for the updates to kick in.
Note that 2 of the if else function will execute only once. All the if-else function have very little code in it. Below is the code
public void positionUpdated(Coordinate userPosition, int accuracy) {
// GETS EXECUTED ONCE //
if(nameList.size() == 0) {nameList = indoorsFragment.getZones();}
if(end == null) {
for(int i=0 ; i < nameList.size() ; i++) if(nameList.get(i).equals(name)) end = nameList.get(i).getZonePoints().get(0);
}
// GETS EXECUTED ONCE //
if(Math.abs(userPosition.x - end.x) >500) {Toast.makeText(this,"WALK " + Math.abs(end.x - userPosition.x)/1000 + " Meters" , Toast.LENGTH_SHORT).show();return;}
if(turn) {
if ((userPosition.y - end.y) < 0) {Toast.makeText(this, "STOP AND TURN RIGHT", Toast.LENGTH_LONG).show();turn=false;return;}
if ((userPosition.y - end.y) > 0) {Toast.makeText(this, "STOP AND TURN LEFT" , Toast.LENGTH_LONG).show();turn=false;return;}
}
if((Math.abs(userPosition.y - end.y) < 500)) Toast.makeText(this, "WALK", Toast.LENGTH_LONG).show();
}
Hope to receive some feedback regarding this , thanks
Haziq
The number of statements doesn't really matter, in fact they're executed in fractions of nanoseconds. what matters is if you have many nested loops or recursions.
If you don't want much work to be done in the foreground thread, use an AsyncTask or Runnable then update the UI in the main thread.
I am currently building a game in AndEngine, but my collision detection seems a bit off. It works.. most of the time, but seems like when there is a collision with one object, it wont do the other. It's hard to explain and it's very unpredictable.
for (int i = 0; i < rManager.carArray.length; i++)
{
if (rManager.getInstance().snowArray[0].getSnowSprite().collidesWith(rManager.getInstance().carArray[i].getCarSprite()))
{
Log.e("SNOW", "snow 0 collided with " + rManager.getInstance().carArray[i].ToString());
rManager.getInstance().carArray[i].setCarSpeed(0.1f);
break;
}
if (rManager.getInstance().iceArray[0].getIceSprite().collidesWith(rManager.getInstance().carArray[i].getCarSprite()))
{
Log.e("ICE", "ice 0 collided with " + rManager.getInstance().carArray[i].ToString());
rManager.getInstance().carArray[i].setCarSpeed(1f);
break;
}
else
{
rManager.getInstance().carArray[i].setCarSpeed(0.5f);
}
}
Is there anything wrong with my code? Currently, both enemy arrays only have 1 element. That is why I am only checking 0.
It is because of the "break" keyword. When that is called it "breaks out" of the surrounding for loop. So if the first if statement detects a collision, it will not ever call the second if statement.
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.