如何统计已饮用杯数并存储总饮水量?含水位数据处理场景
Let's break down how to implement your water tracking feature step by step, building on the code snippet you provided:
1. Parse the Incoming String to an Integer mL Value
First, we'll complete the string parsing logic. Assuming your incoming text string is split by commas and one of the parts contains the numeric water level value (let's say it's the first part for this example), we'll convert it to an integer representing mL:
String text = new String(txValue, "UTF-8"); String[] parts = text.split(","); // Assume parts[0] holds the numeric value (adjust index as needed for your data format) int waterLevelMl = Integer.parseInt(parts[0].trim());
Note: If your raw value is in a different unit (e.g., liters), add a conversion step here (e.g., waterLevelMl = (int)(Double.parseDouble(parts[0]) * 1000);)
2. Update TextBox and Progress Bar
Next, display the mL value in your textbox and update the progress bar to reflect the current water level. You'll need to define a maximum capacity for your container (e.g., 2000mL for a standard bottle):
// Update TextBox with mL value yourTextBox.setText(waterLevelMl + " mL"); // Update Progress Bar (replace MAX_CAPACITY with your container's total mL) final int MAX_CAPACITY = 2000; int progress = (int) (((double) waterLevelMl / MAX_CAPACITY) * 100); yourProgressBar.setProgress(progress);
3. Track Consumed Cups and Total Intake
To track cups consumed and store total intake, you'll need to maintain state variables (declare these as class-level variables so they persist between updates):
// Class-level variables to track consumption private int cupCount = 0; private int totalConsumedMl = 0; private List<Integer> dailyConsumption = new ArrayList<>(); // Array-like storage for intake private int previousWaterLevelMl = MAX_CAPACITY; // Initialize with full capacity
Then, calculate the amount consumed each time you get a new water level reading (assuming the reading is the remaining water):
// Calculate consumed amount since last reading int consumedMl = previousWaterLevelMl - waterLevelMl; // Only track positive consumption (ignore if level increased, e.g., refilling) if (consumedMl > 0) { totalConsumedMl += consumedMl; dailyConsumption.add(consumedMl); // Add to array/list // Update cup count (each cup = 400mL) cupCount = totalConsumedMl / 400; // Integer division gives full cups consumed // If you want to count partial cups as well, use Math.round((double)totalConsumedMl /400) } // Update previous level for next calculation previousWaterLevelMl = waterLevelMl;
Key Notes:
- If your incoming string directly represents the amount consumed (instead of remaining water), skip the
previousWaterLevelMllogic and just add the parsed value tototalConsumedMl. - The
dailyConsumptionlist acts as an array to store each individual intake event. You can convert it to a primitive array later if needed withdailyConsumption.stream().mapToInt(Integer::intValue).toArray();.
Example Full Integration
Putting it all together in a method (adjust for your activity/fragment context):
private void processWaterReading(byte[] txValue) { final int MAX_CAPACITY = 2000; try { String text = new String(txValue, "UTF-8"); String[] parts = text.split(","); if (parts.length < 1) { // Handle invalid input return; } int waterLevelMl = Integer.parseInt(parts[0].trim()); // Update UI yourTextBox.setText(waterLevelMl + " mL"); int progress = (int) (((double) waterLevelMl / MAX_CAPACITY) * 100); yourProgressBar.setProgress(progress); // Track consumption int consumedMl = previousWaterLevelMl - waterLevelMl; if (consumedMl > 0) { totalConsumedMl += consumedMl; dailyConsumption.add(consumedMl); cupCount = totalConsumedMl / 400; // Optional: Update UI with cup count cupCountTextView.setText("Cups consumed: " + cupCount); } previousWaterLevelMl = waterLevelMl; } catch (UnsupportedEncodingException | NumberFormatException e) { // Handle parsing errors e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者Mark Lupas

