create array of values from heart rate sensor - java

i create an app that use in the SENSOR_HEART_RATE.
my app have one label that display the value of the heart rate, but the problem that i get a lots of values that changed every time, in addition the values change not frequent way.
there is possibility to save some values from the sensor and create array?
here part of my code:
public void onSensorChanged(SensorEvent sensorEvent) {
showHeartRate.setText("my heart rate:" + sensorEvent.values[0]);
int i=0;
while(i<10){
arrayHeartRateValues[i]= sensorEvent.values[0];
i++;
}
}
the problem is that my array have one value and not different values.

I've not played with the sensors of android, but I see a couple things that could be affecting the desired outcome of this.
First, you are using a preset array (arrayHeartRateValues) which will be prebuilt to a set size. Because you are not sure of the amount of sensorEvents you will be capturing, I would recommend using a more flexible option. Personally, I use the ArrayList class for most of those things, and the following code example will have that as well, but you may use whatever you like.
Secondly, You are (as stated in the comments) just setting all the values of the arrayHeartRateValues to be whatever sensorEvent.values[0] is.
Here is how I would handle this.
Somewhere in your code (wherever you initialize the arrayHeartRateValues) try this
ArrayList<SensorEvent> arrayHeartRateValues = new ArrayList<>();
Then in your method that catches the changes try this
public void onSensorChanged(SensorEvent sensorEvent) {
showHeartRate.setText("my heart rate:" + sensorEvent.values[0]);
arrayHeartValues.add(sensorEvent);
}
This should have the desired outcome.

Related

Multiplication Field in Java / SceneBuilder

I'm a java Beginner and I've created a program where you can type in some food in a TableView and the details of the respective food you can type in a GripPane. One of the Details you have to type in is the quantity of the food, and another is the Calories per piece. Now I would like to create a button and a field. Or Maybe just a field that shows all calories of the food in the Table view. So it should multiplicate the quantity with the calories, for every food and add them all together. For a Total of Calories. Now I have no idea how to do that. Could somebody help me with step-by-step instructions? Not sure if it makes sense to add some code to the program. By the way, I use Eclipse on Windows and SceneBuilder. Thanks for every help.
Cheers Blarg
The first piece of advice from my side would be to try writing some code on your own! That way you learn and you wouldn't need to copy and paste somebody else's code.
And secondly, this is how I would approach it:
Create the fields as you described below in the Scene Builder and give them all id (names) so that we can access them in our controller (I am supposing you know how that works).
Add a button so that the user can click to perform the calculation
When the button is clicked, you can get all the information from each TextBox and create a Food Object with all the information. Performing the calculation is a rather simple task that can be done by converting the data received from the TextBoxes into numbers and multiplying
public void addFoodItemIntoTable()
{
...
String quantityOfFoodStr = quantityTextBox.getText();
int quantityOfFood = Integer.parseInt(quantityOfFoodStr);
String caloriesOfFoodStr = caloriesTextBox.getText();
double caloriesOfFood = Double.parseDouble(caloriesOfFoodStr);
double total = quantityOfFood * caloriesOfFood;
...
}
After adding all the elements in your TableView (Check this). You can easily get the total of the field by iterating all the elements of your table and adding them into a variable.
Example:
double total = 0;
for(Food currentFood : foodTable.getItems())
{
total = total + currentFood.getTotalCalculation(); // The naming should not be correct... Change it to whatever you find suitable
}
Good luck!

Getting the sum from gwt table element

I have a table written in GWT from a List list. What i want it is to obtain the sum of a certain group of elements.
The problem with this, it is that the value I want to do the sum with its calculated, and thus not obtainable unless you calculate it before generating the List.
I was wondering if it was somehow possible to achieve this through DOM manipulation. And if so, how?.
I will show you an example:
DataA DataB DataC DataD
---------------------------------
aaaaa bbbbb ccccc 12
aaaa1 bbbb1 cccc1 15
aaa11 bbb11 ccc11 17
I want to get the sum of "DataD" column, but i dont know how can i do it.
Thank you in advance for your time,
Kind regards,
Elaborate: DataD column value it is calculated and the value comes from another system and its placed into the table through a third party program; thus i cannot get its value and use it into a sum to get the value i want.
You should be able to add some event handler to the table's widget so that whenever data is added/changed in the widget, you adjust the total. Please give more information about what widgets you are using to represent the table.
EDIT:
now that we know you are using an HTMLLayoutContainer, I assume DataD is being poopulated at a place beyond your controll in code. What you can do is add event handlers to handle the add remove etc events. For example, you could do something like below:
//Your container
HtmlLayoutContainer c = new HtmlLayoutContainer(templates.getTemplate());
c.addAddHandler(new AddEvent.AddHandler() {
#Override
public void onAdd(AddEvent event) {
//Do proper exception handling, check if it is the right widget for dataD, do the needed calculations etc
sum += Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
c.addRemoveHandler(new RemoveEvent.RemoveHandler() {
#Override
public void onRemove(RemoveEvent event) {
//handle all conditions like in onAdd in AddHandler above
sum -= Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
You can look into the API to see what exactl events match your needs best (http://dev.sencha.com/deploy/gxt-3.0.0/javadoc/gxt/com/sencha/gxt/widget/core/client/container/HtmlLayoutContainer.html)

Blacklist strings in an array on android

I have an app that I have made for friends to randomize races for a board game, such that a player gets a randomly selected species every time. I want to include a feature in an update that will allow for a blacklist so that certain races cannot be chosen. What would be the best way to go about this? I'll take any and all advice. Much thanks in advance.
Of note: The array consists of strings of names, and I'd like for this to be persistent for as long as they have the app installed or until they change it.
Edit: Apologies for my lack of clarity. I know generally how I need to do it, but what about saving the settings from the settings menu so that upon closing and reopening, blacklisted races are persistent? Even when the app is closed, upon reopening I'd like for the settings to stay the same. That way next time they play the game (weeks later), assuming their tastes haven't changed, they can go to clicking without blacklisting again.
Without any code, it's hard to say for sure how to go about this, because I don't know how you're implementing the rest of the app.
One way I can think of doing this is if you associate an integer with each race, e.g. by using constants:
public static final GIRAFFE = 1;
public static final GOOSE = 2;
Then you could generate random integers to randomly pick each race. If you created a method for the random integer generation, you could then pass certain numbers that would be excluded. You could keep generating a random integer while the integer generated was one of the excluded numbers.
E.g. (Since it's Android I'll code in Java)
// assume min = smallest integer assigned to an animal,
// and max = largest integer assigned to an animal
public static int randomNumber(int ... exclude)
{
int random = min + (int)(Math.random() * ((max - min) + 1));
for (int i = 0; i < exclude.length; i++)
{
if (exclude[i] == random)
random = Min + (int)(Math.random() * ((Max - Min) + 1));
}
return random;
}
I'm a little new to StackOverflow, so let me know if this helps.
What you need to do is persist data. You can use two solutions:
1) The SharedPreferences framework for saving key-value pairs without any effort. See here to see how to save a list Store a List or Set in SharedPreferences
2) use SQL database. (custom solution)
In case 1 you would persist the blacklisted strings and in case 2 you would be best to create a table with all strings and have a boolean as to whether its blacklisted or not.
I recommend the shared preferences one since it should take you 5 min to do whereas, unless you are familiar with databases, the database solution will take you a while to work out.

I would like the Arrays to remember it all

This is about my assignment so I would appreciate generic answers with explanation.
I have a for-loop which I have to make for an online ordering system. The for-loop and ordering all works fine but if the same item is put in twice, then it forgets the previous order for the same item and only remembers the latest one. I am required to use simple arrays and for-loops so I would appreciate if the solution/help was also of this basic level.
My code looks something like this (NOTE: The following is just an example of what part of the loop looks like--this is not a complete program):
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
int price = quantity[i] + itemcode;
}
}
To explain further, this loop and the if statement work perfectly if a certain item is only ordered once. But if the user enters, say, an order for a computer once and then after 3 more orders, orders another computer, then the output does not add the previous order in the new order but only remembers the latest one.
I would appreciate any work around suggested for this but again, since this is for my studies, I would appreciate explanations rather than direct solutions.
Please ask me questions in case this is not clear.
"Forgets" suggests that you are overwriting something in your code rather than, say, just incrementing. Go through your code, see what parts of it gets reset when you place a new order. For instance, if you are doing
quantity[1] = getNumberFromUser("How many apples?");
then this would obviously erase the old value each time. If you want to merely increment the number of apples, do something like
quantity[1] += getNumberFromUser("How many apples?");
Another general advice is to use print statements to debug your code. That way you can see for yourself what really happens. Learning to use a real debugger would also be of great benefit.
if you have two or more typres of products and want to calculate the price for all the orders together then you can try the following code,, i think thats very simple,,
int price=0;
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
price += quantity[i] + itemcode; //use the previous value of price
}
}
or else if you want to have history for each product separately then you have to try the same with a array of price for each product type..
If you cant get the answer then comment here,,

find nearest Gps point to the user location form a list

what i am trying to do: the user selects start and destination on a map and then from their coordinates i want to show the closest point location from a list of locations on map. i have a simple Sqlite database containing the longitude,latitude and name of the possible locations.
i did some research and this is what i found:
http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
but this is meant for using it with mySql and some kind of spatial search extension.
is there a possibility i can do something similar using android api or external libs?
public Point dialogFindClosestLocationToPoint(geometry.Point aStartPoint){
List<PointWithDistance> helperList=new ArrayList<PointWithDistance>();
try {
openDataBase();
Cursor c=getCursorQueryWithAllTheData();
if(c.moveToFirst())
do{
PointWithDistance helper=new PointWithDistance(c.getDouble(1),c.getDouble(2),c.getString(3));
int distance=returnDistanceBetween2Points(aStartPoint, helper);
if(distance<MAX_SEARCH_DISTANCE){
helper.setDistance(distance);
Log.i("values", helper.name);
helperList.add(helper);
}
}while (c.moveToNext());
Collections.sort(helperList,new PointComparator());
if(helperList!=null)
return helperList.get(0);
else return null;
}catch(SQLException sqle){
throw sqle;
}
finally{
close();
}
this is the code in the PointComparator() class:
public int compare(PointWithDistance o1, PointWithDistance o2) {
return (o1.getDistance()<o2.getDistance() ? -1 : (o1.getDistance()==o2.getDistance() ? 0 : 1));
}
where PointWithDistance is a object that contains: lat, long , distance, name
however this solution doesn't provide the right return info... and i realize that is it not scalable at all and very slow. i need a solution that will execute fast with a database with max of 1000 rows.
edit: my there was a mistake in this code in the sorting now i have it changed( should be < instead of >)
This kind of thing is done most efficiently using an R-Tree. The JSI library provides a Java implementation that I have used successfully with an index of 80.000 locations, processing thousands of lookups per second. However, it may not run on Android.
I was looking for something very similar some time ago:
Android sqlite sort on calculated column (co-ordinates distance)
I was using a MySQL lookup on my server, MySQL allows you to create a virtual column, performs the calculation and sorts by distance, and then you can set the max results returned or the max distance - it works very well:
Select Lat, Lon, acos(sin($lat)*sin(radians(Lat)) + cos($lat)*cos(radians(Lat))cos(radians(Lon)-$lon))$R As dist From MyTable ORDER BY dist DESC
I wanted to perform the same operation in my app - pull all the points in order to distance from the users location allowing me to show the closest ones. I ended up going with the a solution along the lines of the one suggested on the link above but realise its probably not the optimal solution but works for the purpose I wanted.
i haven't tried running your code, but it seems like it would work, it's just that it's not efficient. like you don't actually need to sort, you need the extract the minimum.
you can restrict your query to just the square that is of size (2*MAX_SEARCH_DISTANCE)^2 (with your point in the middle.
This way you are localizing your query and that will return you less results to compute distance for.
Of course this will not help if all your locations are in the localized square (maybe unlikely?).
Also, I suppose you could use hamiltonian distance instead of euclidean.
euclidean distance = sqrt((lat0 - lat1)^2 + (lon0 - lon1)^2)
hamitonian distance = (lat0 - lat1) + (lon0 - lon1)

Categories

Resources