1
0
mirror of https://github.com/oliexdev/openScale.git synced 2025-09-02 12:54:10 +02:00
This commit is contained in:
OliE
2017-11-26 07:59:14 +01:00
26 changed files with 727 additions and 735 deletions

View File

@@ -52,40 +52,40 @@ import java.util.TreeMap;
public class OpenScale { public class OpenScale {
private static OpenScale instance; private static OpenScale instance;
private ScaleDatabase scaleDB; private ScaleDatabase scaleDB;
private ScaleUserDatabase scaleUserDB; private ScaleUserDatabase scaleUserDB;
private ArrayList<ScaleData> scaleDataList; private ArrayList<ScaleData> scaleDataList;
private BluetoothCommunication btCom; private BluetoothCommunication btCom;
private String btDeviceName; private String btDeviceName;
private AlarmHandler alarmHandler; private AlarmHandler alarmHandler;
private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
private Context context; private Context context;
private ArrayList<FragmentUpdateListener> fragmentList; private ArrayList<FragmentUpdateListener> fragmentList;
private OpenScale(Context context) { private OpenScale(Context context) {
this.context = context; this.context = context;
scaleDB = new ScaleDatabase(context); scaleDB = new ScaleDatabase(context);
scaleUserDB = new ScaleUserDatabase(context); scaleUserDB = new ScaleUserDatabase(context);
alarmHandler = new AlarmHandler(); alarmHandler = new AlarmHandler();
btCom = null; btCom = null;
fragmentList = new ArrayList<>(); fragmentList = new ArrayList<>();
updateScaleData(); updateScaleData();
} }
public static OpenScale getInstance(Context context) { public static OpenScale getInstance(Context context) {
if (instance == null) { if (instance == null) {
instance = new OpenScale(context); instance = new OpenScale(context);
} }
return instance; return instance;
} }
public void addScaleUser(String name, Date birthday, int body_height, int scale_unit, int gender, float initial_weight, float goal_weight, Date goal_date) public void addScaleUser(String name, Date birthday, int body_height, int scale_unit, int gender, float initial_weight, float goal_weight, Date goal_date)
{ {
@@ -156,9 +156,9 @@ public class OpenScale {
} }
public ArrayList<ScaleData> getScaleDataList() { public ArrayList<ScaleData> getScaleDataList() {
return scaleDataList; return scaleDataList;
} }
public ScaleData[] getTupleScaleData(long id) public ScaleData[] getTupleScaleData(long id)
@@ -166,7 +166,7 @@ public class OpenScale {
return scaleDB.getTupleDataEntry(getSelectedScaleUser().id, id); return scaleDB.getTupleDataEntry(getSelectedScaleUser().id, id);
} }
public int addScaleData(ScaleData scaleData) { public int addScaleData(ScaleData scaleData) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
@@ -201,7 +201,7 @@ public class OpenScale {
scaleData.setFat(fatMetric.getFat(getScaleUser(scaleData.getUserId()), scaleData)); scaleData.setFat(fatMetric.getFat(getScaleUser(scaleData.getUserId()), scaleData));
} }
if (scaleDB.insertEntry(scaleData)) { if (scaleDB.insertEntry(scaleData)) {
ScaleUser scaleUser = getScaleUser(scaleData.getUserId()); ScaleUser scaleUser = getScaleUser(scaleData.getUserId());
String infoText = String.format(context.getString(R.string.info_new_data_added), scaleData.getConvertedWeight(scaleUser.scale_unit), scaleUser.UNIT_STRING[scaleUser.scale_unit], dateTimeFormat.format(scaleData.getDateTime()), scaleUser.user_name); String infoText = String.format(context.getString(R.string.info_new_data_added), scaleData.getConvertedWeight(scaleUser.scale_unit), scaleUser.UNIT_STRING[scaleUser.scale_unit], dateTimeFormat.format(scaleData.getDateTime()), scaleUser.user_name);
@@ -211,7 +211,7 @@ public class OpenScale {
} }
return scaleData.getUserId(); return scaleData.getUserId();
} }
private int getSmartUserAssignment(float weight, float range) { private int getSmartUserAssignment(float weight, float range) {
ArrayList<ScaleUser> scaleUser = getScaleUserList(); ArrayList<ScaleUser> scaleUser = getScaleUserList();
@@ -263,31 +263,31 @@ public class OpenScale {
updateScaleData(); updateScaleData();
} }
public void importData(String filename) throws IOException { public void importData(String filename) throws IOException {
File file = new File(filename); File file = new File(filename);
FileInputStream inputStream = new FileInputStream(file); FileInputStream inputStream = new FileInputStream(file);
InputStreamReader inputReader = new InputStreamReader(inputStream); InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader csvReader = new BufferedReader(inputReader); BufferedReader csvReader = new BufferedReader(inputReader);
String line = csvReader.readLine(); String line = csvReader.readLine();
try { try {
while (line != null) { while (line != null) {
String csvField[] = line.split(",", -1); String csvField[] = line.split(",", -1);
if (csvField.length < 9) { if (csvField.length < 9) {
throw new IOException("Can't parse CSV file. Field length is wrong."); throw new IOException("Can't parse CSV file. Field length is wrong.");
} }
ScaleData newScaleData = new ScaleData(); ScaleData newScaleData = new ScaleData();
newScaleData.setDateTime(dateTimeFormat.parse(csvField[0])); newScaleData.setDateTime(dateTimeFormat.parse(csvField[0]));
newScaleData.setWeight(Float.parseFloat(csvField[1])); newScaleData.setWeight(Float.parseFloat(csvField[1]));
newScaleData.setFat(Float.parseFloat(csvField[2])); newScaleData.setFat(Float.parseFloat(csvField[2]));
newScaleData.setWater(Float.parseFloat(csvField[3])); newScaleData.setWater(Float.parseFloat(csvField[3]));
newScaleData.setMuscle(Float.parseFloat(csvField[4])); newScaleData.setMuscle(Float.parseFloat(csvField[4]));
newScaleData.setLBW(Float.parseFloat(csvField[5])); newScaleData.setLBW(Float.parseFloat(csvField[5]));
newScaleData.setBone(Float.parseFloat(csvField[6])); newScaleData.setBone(Float.parseFloat(csvField[6]));
newScaleData.setWaist(Float.parseFloat(csvField[7])); newScaleData.setWaist(Float.parseFloat(csvField[7]));
@@ -296,14 +296,14 @@ public class OpenScale {
newScaleData.setUserId(getSelectedScaleUser().id); newScaleData.setUserId(getSelectedScaleUser().id);
scaleDB.insertEntry(newScaleData); scaleDB.insertEntry(newScaleData);
line = csvReader.readLine(); line = csvReader.readLine();
} }
} catch (ParseException e) { } catch (ParseException e) {
throw new IOException("Can't parse date format. Please set the date time format as <dd.MM.yyyy HH:mm> (e.g. 31.10.2014 05:23)"); throw new IOException("Can't parse date format. Please set the date time format as <dd.MM.yyyy HH:mm> (e.g. 31.10.2014 05:23)");
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new IOException("Can't parse float number (" + e.getMessage()+")"); throw new IOException("Can't parse float number (" + e.getMessage()+")");
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Can't parse format column number mismatch"); throw new IOException("Can't parse format column number mismatch");
@@ -311,24 +311,24 @@ public class OpenScale {
updateScaleData(); updateScaleData();
csvReader.close(); csvReader.close();
inputReader.close(); inputReader.close();
} }
public void exportData(String filename) throws IOException { public void exportData(String filename) throws IOException {
File file = new File(filename); File file = new File(filename);
file.createNewFile(); file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file); FileOutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter csvWriter = new OutputStreamWriter(outputStream); OutputStreamWriter csvWriter = new OutputStreamWriter(outputStream);
for (ScaleData scaleData : scaleDataList) { for (ScaleData scaleData : scaleDataList) {
csvWriter.append(dateTimeFormat.format(scaleData.getDateTime()) + ","); csvWriter.append(dateTimeFormat.format(scaleData.getDateTime()) + ",");
csvWriter.append(Float.toString(scaleData.getWeight()) + ","); csvWriter.append(Float.toString(scaleData.getWeight()) + ",");
csvWriter.append(Float.toString(scaleData.getFat()) + ","); csvWriter.append(Float.toString(scaleData.getFat()) + ",");
csvWriter.append(Float.toString(scaleData.getWater()) + ","); csvWriter.append(Float.toString(scaleData.getWater()) + ",");
csvWriter.append(Float.toString(scaleData.getMuscle()) + ","); csvWriter.append(Float.toString(scaleData.getMuscle()) + ",");
csvWriter.append(Float.toString(scaleData.getLBW()) + ","); csvWriter.append(Float.toString(scaleData.getLBW()) + ",");
csvWriter.append(Float.toString(scaleData.getBone()) + ","); csvWriter.append(Float.toString(scaleData.getBone()) + ",");
csvWriter.append(Float.toString(scaleData.getWaist()) + ","); csvWriter.append(Float.toString(scaleData.getWaist()) + ",");
@@ -337,20 +337,20 @@ public class OpenScale {
csvWriter.append(scaleData.getComment()); csvWriter.append(scaleData.getComment());
} }
csvWriter.append("\n"); csvWriter.append("\n");
} }
csvWriter.close(); csvWriter.close();
outputStream.close(); outputStream.close();
} }
public void clearScaleData(int userId) { public void clearScaleData(int userId) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt("uniqueNumber", 0x00).commit(); prefs.edit().putInt("uniqueNumber", 0x00).commit();
scaleDB.clearScaleData(userId); scaleDB.clearScaleData(userId);
updateScaleData(); updateScaleData();
} }
public int[] getCountsOfMonth(int year) { public int[] getCountsOfMonth(int year) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
@@ -373,8 +373,8 @@ public class OpenScale {
return scaleDB.getScaleDataOfYear(selectedUserId, year); return scaleDB.getScaleDataOfYear(selectedUserId, year);
} }
public boolean startSearchingForBluetooth(String deviceName, Handler callbackBtHandler) { public boolean startSearchingForBluetooth(String deviceName, Handler callbackBtHandler) {
Log.d("OpenScale", "Bluetooth Server started! I am searching for device ..."); Log.d("OpenScale", "Bluetooth Server started! I am searching for device ...");
for (BluetoothCommunication.BT_DEVICE_ID btScaleID : BluetoothCommunication.BT_DEVICE_ID.values()) { for (BluetoothCommunication.BT_DEVICE_ID btScaleID : BluetoothCommunication.BT_DEVICE_ID.values()) {
btCom = BluetoothCommunication.getBtDevice(context, btScaleID); btCom = BluetoothCommunication.getBtDevice(context, btScaleID);
@@ -392,12 +392,12 @@ public class OpenScale {
return false; return false;
} }
public void stopSearchingForBluetooth() { public void stopSearchingForBluetooth() {
if (btCom != null) { if (btCom != null) {
btCom.stopSearching(); btCom.stopSearching();
Log.d("OpenScale", "Bluetooth Server explicit stopped!"); Log.d("OpenScale", "Bluetooth Server explicit stopped!");
} }
} }
public void registerFragment(FragmentUpdateListener fragment) { public void registerFragment(FragmentUpdateListener fragment) {
fragmentList.add(fragment); fragmentList.add(fragment);
@@ -417,7 +417,7 @@ public class OpenScale {
scaleDataList = scaleDB.getScaleDataList(selectedUserId); scaleDataList = scaleDB.getScaleDataList(selectedUserId);
for(FragmentUpdateListener fragment : fragmentList) { for (FragmentUpdateListener fragment : fragmentList) {
if (fragment != null) { if (fragment != null) {
if (((Fragment)fragment).isAdded()) { if (((Fragment)fragment).isAdded()) {
fragment.updateOnView(scaleDataList); fragment.updateOnView(scaleDataList);

View File

@@ -59,10 +59,10 @@ public class AlarmHandler
Calendar dataTimestamp = Calendar.getInstance(); Calendar dataTimestamp = Calendar.getInstance();
dataTimestamp.setTimeInMillis(dataMillis); dataTimestamp.setTimeInMillis(dataMillis);
if(AlarmHandler.isSameDate(dataTimestamp, Calendar.getInstance())) if (AlarmHandler.isSameDate(dataTimestamp, Calendar.getInstance()))
{ {
cancelAlarmNotification(context); cancelAlarmNotification(context);
cancelAndRescheduleAlarmForNextWeek( context, dataTimestamp ); cancelAndRescheduleAlarmForNextWeek(context, dataTimestamp);
} }
} }

View File

@@ -242,7 +242,7 @@ public abstract class BluetoothCommunication {
* @param gattCharacteristic the Bluetooth Gatt characteristic * @param gattCharacteristic the Bluetooth Gatt characteristic
* @param status the status code * @param status the status code
*/ */
protected void onBluetoothDataRead(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic, int status){}; protected void onBluetoothDataRead(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic, int status) {};
/** /**
* Method is triggered if a Bluetooth data from a device is notified or indicated. * Method is triggered if a Bluetooth data from a device is notified or indicated.
@@ -250,7 +250,7 @@ public abstract class BluetoothCommunication {
* @param bluetoothGatt the Bluetooth Gatt * @param bluetoothGatt the Bluetooth Gatt
* @param gattCharacteristic the Bluetooth characteristic * @param gattCharacteristic the Bluetooth characteristic
*/ */
protected void onBluetoothDataChange(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic){}; protected void onBluetoothDataChange(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic) {};
/** /**
* Set the Bluetooth machine state to a specific state. * Set the Bluetooth machine state to a specific state.
@@ -371,7 +371,7 @@ public abstract class BluetoothCommunication {
} }
final StringBuilder stringBuilder = new StringBuilder(data.length); final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data) { for (byte byteChar : data) {
stringBuilder.append(String.format("%02X ", byteChar)); stringBuilder.append(String.format("%02X ", byteChar));
} }

View File

@@ -133,7 +133,7 @@ public class BluetoothDigooDGSO38H extends BluetoothCommunication {
ScaleData scaleBtData = new ScaleData(); ScaleData scaleBtData = new ScaleData();
weight = (float) (((weightBytes[3] & 0xFF) << 8) | (weightBytes[4] & 0xFF)) / 100.0f; weight = (float) (((weightBytes[3] & 0xFF) << 8) | (weightBytes[4] & 0xFF)) / 100.0f;
fat = (float) (((weightBytes[6] & 0xFF) << 8) | (weightBytes[7] & 0xFF)) / 10.0f; fat = (float) (((weightBytes[6] & 0xFF) << 8) | (weightBytes[7] & 0xFF)) / 10.0f;
if(Math.abs(fat - 0.0) < 0.00001) { if (Math.abs(fat - 0.0) < 0.00001) {
Log.d("BluetoothDigooDGSO38H", "Scale signaled that measurement of all data " + Log.d("BluetoothDigooDGSO38H", "Scale signaled that measurement of all data " +
"is done, but fat ist still zero. Settling for just adding weight."); "is done, but fat ist still zero. Settling for just adding weight.");
} else { } else {

View File

@@ -1,18 +1,18 @@
/* Copyright (C) 2014 olie.xdev <olie.xdev@googlemail.com> /* Copyright (C) 2014 olie.xdev <olie.xdev@googlemail.com>
* 2017 DreamNik <dreamnik@mail.ru> * 2017 DreamNik <dreamnik@mail.ru>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
*/ */
package com.health.openscale.core.bluetooth; package com.health.openscale.core.bluetooth;
@@ -33,198 +33,195 @@ import java.util.UUID;
public class BluetoothMGB extends BluetoothCommunication { public class BluetoothMGB extends BluetoothCommunication {
static final UUID uuid_service = UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb"); static final UUID uuid_service = UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb");
static final UUID uuid_char_cfg = UUID.fromString("0000ffb1-0000-1000-8000-00805f9b34fb"); static final UUID uuid_char_cfg = UUID.fromString("0000ffb1-0000-1000-8000-00805f9b34fb");
static final UUID uuid_char_ctrl = UUID.fromString("0000ffb2-0000-1000-8000-00805f9b34fb"); static final UUID uuid_char_ctrl = UUID.fromString("0000ffb2-0000-1000-8000-00805f9b34fb");
static final UUID uuid_desc_ctrl = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); static final UUID uuid_desc_ctrl = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
private Calendar now; private Calendar now;
private ScaleUser user; private ScaleUser user;
private ScaleData measurement; private ScaleData measurement;
private byte[] packet_buf; private byte[] packet_buf;
private int packet_pos; private int packet_pos;
private int popInt( ){ private int popInt() {
return packet_buf[packet_pos++] & 0xFF; return packet_buf[packet_pos++] & 0xFF;
} }
private float popFloat( ){ private float popFloat() {
int r = popInt(); int r = popInt();
r = popInt() | (r<<8); r = popInt() | (r<<8);
return r * 0.1f; return r * 0.1f;
} }
private void writeCfg( int b2 , int b3 , int b4 , int b5 ){ private void writeCfg(int b2, int b3, int b4, int b5) {
byte[] buf = new byte[8]; byte[] buf = new byte[8];
buf[0] = (byte)0xAC; buf[0] = (byte)0xAC;
buf[1] = (byte)0x02; buf[1] = (byte)0x02;
buf[2] = (byte)b2; buf[2] = (byte)b2;
buf[3] = (byte)b3; buf[3] = (byte)b3;
buf[4] = (byte)b4; buf[4] = (byte)b4;
buf[5] = (byte)b5; buf[5] = (byte)b5;
buf[6] = (byte)0xCC; buf[6] = (byte)0xCC;
buf[7] = (byte)( ( buf[2] + buf[3] + buf[4] + buf[5] + buf[6] ) & 0xFF ); buf[7] = (byte)((buf[2] + buf[3] + buf[4] + buf[5] + buf[6]) & 0xFF);
writeBytes( uuid_service , uuid_char_cfg , buf ); writeBytes(uuid_service, uuid_char_cfg, buf);
} }
public BluetoothMGB(Context context) {
super(context);
}
@Override
public String deviceName() {
return "SWAN";
}
@Override
public String defaultDeviceName() {
return "SWAN";
}
@Override
public boolean checkDeviceName(String btDeviceName) {
if (btDeviceName.startsWith("SWAN")) {
return true;
}
return false;
}
@Override
boolean nextInitCmd(int stateNr) {
switch (stateNr) {
case 0:
setNotificationOn(uuid_service, uuid_char_ctrl, uuid_desc_ctrl);
now = Calendar.getInstance();
user = OpenScale.getInstance(context).getSelectedScaleUser();
break;
public BluetoothMGB( Context context ){ case 1:
super(context); writeCfg(0xF7, 0, 0, 0);
} break;
@Override case 2:
public String deviceName() { writeCfg(0xFA, 0, 0, 0);
return "SWAN"; break;
}
@Override case 3:
public String defaultDeviceName() { writeCfg(0xFB, (user.isMale() ? 1 : 2), user.getAge(new Date()), user.body_height);
return "SWAN"; break;
}
@Override case 4:
public boolean checkDeviceName(String btDeviceName) { writeCfg(0xFD, now.get(Calendar.YEAR) - 2000, now.get(Calendar.MONTH) - Calendar.JANUARY + 1, now.get(Calendar.DAY_OF_MONTH));
if (btDeviceName.startsWith("SWAN")) { break;
return true;
}
return false; case 5:
} writeCfg(0xFC, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
break;
case 6:
writeCfg(0xFE, 6, 1, 0);
break;
default:
return false;
}
return true;
}
@Override
@Override boolean nextBluetoothCmd(int stateNr) {
boolean nextInitCmd(int stateNr) { return false;
switch (stateNr) { }
case 0:
setNotificationOn( uuid_service , uuid_char_ctrl , uuid_desc_ctrl );
now = Calendar.getInstance();
user = OpenScale.getInstance(context).getSelectedScaleUser();
break;
case 1:
writeCfg( 0xF7 , 0 , 0 , 0 );
break;
case 2:
writeCfg( 0xFA , 0 , 0 , 0 );
break;
case 3:
writeCfg( 0xFB , (user.isMale() ? 1 : 2) , user.getAge(new Date()) , user.body_height );
break;
case 4:
writeCfg( 0xFD , now.get( Calendar.YEAR ) - 2000 , now.get( Calendar.MONTH ) - Calendar.JANUARY + 1 , now.get( Calendar.DAY_OF_MONTH ) );
break;
case 5:
writeCfg( 0xFC , now.get( Calendar.HOUR_OF_DAY ) , now.get( Calendar.MINUTE ) , now.get( Calendar.SECOND ) );
break;
case 6:
writeCfg( 0xFE , 6 , 1 , 0 );
break;
default:
return false;
}
return true;
}
@Override @Override
boolean nextBluetoothCmd(int stateNr) { boolean nextCleanUpCmd(int stateNr) {
return false; return false;
} }
@Override @Override
boolean nextCleanUpCmd(int stateNr) { public void onBluetoothDataChange(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic) {
return false; packet_buf = gattCharacteristic.getValue();
} packet_pos = 0;
if (packet_buf == null || packet_buf.length <= 0) {
return;
}
@Override if (packet_buf.length != 20) {
public void onBluetoothDataChange(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic) { return;
packet_buf = gattCharacteristic.getValue(); }
packet_pos = 0;
if( packet_buf == null || packet_buf.length <= 0 ){ int hdr_1 = popInt();
return; int hdr_2 = popInt();
} int hdr_3 = popInt();
if( packet_buf.length != 20 ){ if (hdr_1 == 0xAC && hdr_2 == 0x02 && hdr_3 == 0xFF) {
return; measurement = new ScaleData();
}
int hdr_1 = popInt(); popInt(); //unknown =00
int hdr_2 = popInt(); popInt(); //unknown =02
int hdr_3 = popInt(); popInt(); //unknown =21
if( hdr_1 == 0xAC && hdr_2 == 0x02 && hdr_3 == 0xFF ){ popInt(); //Year
measurement = new ScaleData(); popInt(); //Month
popInt(); //Day
popInt(); //Hour
popInt(); //Minute
popInt(); //Second
popInt(); //unknown =00 measurement.setDateTime(new Date());
popInt(); //unknown =02
popInt(); //unknown =21
popInt(); //Year measurement.setWeight(popFloat());
popInt(); //Month
popInt(); //Day
popInt(); //Hour
popInt(); //Minute
popInt(); //Second
measurement.setDateTime( new Date() ); popFloat(); //BMI
measurement.setWeight( popFloat() ); measurement.setFat(popFloat());
popFloat(); //BMI popInt(); //unknown =00
popInt(); //unknown =00
measurement.setFat( popFloat() ); } else if (hdr_1 == 0x01 && hdr_2 == 0x00) {
measurement.setMuscle(popFloat());
popInt(); //unknown =00 popFloat(); //BMR
popInt(); //unknown =00
}else measurement.setBone(popFloat());
if( hdr_1 == 0x01 && hdr_2 == 0x00 ){
measurement.setMuscle( popFloat() );
popFloat(); //BMR measurement.setWater(popFloat());
measurement.setBone( popFloat() ); popInt(); // Age
measurement.setWater( popFloat() ); popFloat();// protein rate
popInt(); // Age popInt(); // unknown =00
popInt(); // unknown =01
popInt(); // unknown =1b
popInt(); // unknown =a5
popInt(); // unknown =02
popInt(); // unknown =47;48;4e;4b;42
popFloat();// protein rate addScaleData(measurement);
popInt(); // unknown =00 // Visceral fat?
popInt(); // unknown =01 // Standart weight?
popInt(); // unknown =1b // WeightControl?
popInt(); // unknown =a5 // Body fat?
popInt(); // unknown =02 // Muscle weight?
popInt(); // unknown =47;48;4e;4b;42 }
}
addScaleData( measurement );
// Visceral fat?
// Standart weight?
// WeightControl?
// Body fat?
// Muscle weight?
}
}
} }

View File

@@ -60,12 +60,12 @@ public class BluetoothMedisanaBS444 extends BluetoothCommunication {
} }
@Override @Override
boolean nextInitCmd(int stateNr){ boolean nextInitCmd(int stateNr) {
return false; return false;
} }
@Override @Override
boolean nextBluetoothCmd(int stateNr){ boolean nextBluetoothCmd(int stateNr) {
switch (stateNr) { switch (stateNr) {
case 0: case 0:
// set indication on for feature characteristic // set indication on for feature characteristic
@@ -82,7 +82,7 @@ public class BluetoothMedisanaBS444 extends BluetoothCommunication {
case 3: case 3:
// send magic number to receive weight data // send magic number to receive weight data
Date date = new Date(); Date date = new Date();
int unix_timestamp = (int) ((date.getTime() / 1000) - 1262304000) ; // -40 years because unix time starts in year 1970 int unix_timestamp = (int) ((date.getTime() / 1000) - 1262304000); // -40 years because unix time starts in year 1970
byte[] magicBytes = new byte[] { byte[] magicBytes = new byte[] {
(byte)0x02, (byte)0x02,
@@ -103,13 +103,13 @@ public class BluetoothMedisanaBS444 extends BluetoothCommunication {
} }
@Override @Override
boolean nextCleanUpCmd(int stateNr){ boolean nextCleanUpCmd(int stateNr) {
return false; return false;
} }
@Override @Override
public void onBluetoothDataChange(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic){ public void onBluetoothDataChange(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic gattCharacteristic) {
final byte[] data = gattCharacteristic.getValue(); final byte[] data = gattCharacteristic.getValue();
if (gattCharacteristic.getUuid().equals(WEIGHT_MEASUREMENT_CHARACTERISTIC)) { if (gattCharacteristic.getUuid().equals(WEIGHT_MEASUREMENT_CHARACTERISTIC)) {

View File

@@ -21,7 +21,7 @@ import com.health.openscale.core.datatypes.ScaleUser;
public abstract class EstimatedFatMetric { public abstract class EstimatedFatMetric {
public enum FORMULA { BF_DEURENBERG, BF_DEURENBERG_II, BF_EDDY, BF_GALLAGHER, BF_GALLAGHER_ASIAN }; public enum FORMULA { BF_DEURENBERG, BF_DEURENBERG_II, BF_EDDY, BF_GALLAGHER, BF_GALLAGHER_ASIAN };
public static EstimatedFatMetric getEstimatedMetric( FORMULA metric) { public static EstimatedFatMetric getEstimatedMetric(FORMULA metric) {
switch (metric) { switch (metric) {
case BF_DEURENBERG: case BF_DEURENBERG:
return new BFDeurenberg(); return new BFDeurenberg();

View File

@@ -21,7 +21,7 @@ import com.health.openscale.core.datatypes.ScaleUser;
public abstract class EstimatedWaterMetric { public abstract class EstimatedWaterMetric {
public enum FORMULA { TBW_BEHNKE, TBW_DELWAIDECRENIER, TBW_HUMEWEYERS, TBW_LEESONGKIM }; public enum FORMULA { TBW_BEHNKE, TBW_DELWAIDECRENIER, TBW_HUMEWEYERS, TBW_LEESONGKIM };
public static EstimatedWaterMetric getEstimatedMetric( FORMULA metric) { public static EstimatedWaterMetric getEstimatedMetric(FORMULA metric) {
switch (metric) { switch (metric) {
case TBW_BEHNKE: case TBW_BEHNKE:
return new TBWBehnke(); return new TBWBehnke();

View File

@@ -52,24 +52,24 @@ public class ScaleDatabase extends SQLiteOpenHelper {
private static final String COLUMN_NAME_ENABLE = "enable"; private static final String COLUMN_NAME_ENABLE = "enable";
private static final String SQL_CREATE_ENTRIES = private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" + "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME_USER_ID + " INTEGER," + COLUMN_NAME_USER_ID + " INTEGER," +
COLUMN_NAME_DATE_TIME + " TEXT," + COLUMN_NAME_DATE_TIME + " TEXT," +
COLUMN_NAME_WEIGHT + " REAL," + COLUMN_NAME_WEIGHT + " REAL," +
COLUMN_NAME_FAT + " REAL," + COLUMN_NAME_FAT + " REAL," +
COLUMN_NAME_WATER + " REAL," + COLUMN_NAME_WATER + " REAL," +
COLUMN_NAME_MUSCLE + " REAL," + COLUMN_NAME_MUSCLE + " REAL," +
COLUMN_NAME_LBW + " REAL," + COLUMN_NAME_LBW + " REAL," +
COLUMN_NAME_BONE + " REAL," + COLUMN_NAME_BONE + " REAL," +
COLUMN_NAME_WAIST + " REAL," + COLUMN_NAME_WAIST + " REAL," +
COLUMN_NAME_HIP + " REAL," + COLUMN_NAME_HIP + " REAL," +
COLUMN_NAME_COMMENT + " TEXT," + COLUMN_NAME_COMMENT + " TEXT," +
COLUMN_NAME_ENABLE + " INTEGER" + COLUMN_NAME_ENABLE + " INTEGER" +
")"; ")";
private static final String SQL_DELETE_ENTRIES = private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TABLE_NAME; "DROP TABLE IF EXISTS " + TABLE_NAME;
private static String[] projection = { private static String[] projection = {
@@ -93,17 +93,17 @@ public class ScaleDatabase extends SQLiteOpenHelper {
private SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US); private SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
public ScaleDatabase(Context context) { public ScaleDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION); super(context, DATABASE_NAME, null, DATABASE_VERSION);
} }
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES); db.execSQL(SQL_CREATE_ENTRIES);
} }
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) { if (oldVersion == 1 && newVersion == 2) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_COMMENT + " TEXT DEFAULT ''"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_COMMENT + " TEXT DEFAULT ''");
} }
@@ -124,14 +124,14 @@ public class ScaleDatabase extends SQLiteOpenHelper {
if (oldVersion == 5 && newVersion == 6) { if (oldVersion == 5 && newVersion == 6) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_LBW + " REAL DEFAULT 0"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_LBW + " REAL DEFAULT 0");
} }
} }
public void clearScaleData(int userId) { public void clearScaleData(int userId) {
dbWrite.delete(TABLE_NAME, COLUMN_NAME_USER_ID + "=" + Integer.toString(userId), null); dbWrite.delete(TABLE_NAME, COLUMN_NAME_USER_ID + "=" + Integer.toString(userId), null);
} }
public boolean insertEntry(ScaleData scaleData) { public boolean insertEntry(ScaleData scaleData) {
SQLiteDatabase db = getWritableDatabase(); SQLiteDatabase db = getWritableDatabase();
Cursor cursorScaleDB = db.query(TABLE_NAME, new String[] {COLUMN_NAME_DATE_TIME}, COLUMN_NAME_DATE_TIME + "=? AND " + COLUMN_NAME_USER_ID + "=?", Cursor cursorScaleDB = db.query(TABLE_NAME, new String[] {COLUMN_NAME_DATE_TIME}, COLUMN_NAME_DATE_TIME + "=? AND " + COLUMN_NAME_USER_ID + "=?",
new String[] {formatDateTime.format(scaleData.getDateTime()), Integer.toString(scaleData.getUserId())}, null, null, null); new String[] {formatDateTime.format(scaleData.getDateTime()), Integer.toString(scaleData.getUserId())}, null, null, null);
@@ -170,7 +170,7 @@ public class ScaleDatabase extends SQLiteOpenHelper {
cursorScaleDB.close(); cursorScaleDB.close();
return true; return true;
} }
public void updateEntry(long id, ScaleData scaleData) { public void updateEntry(long id, ScaleData scaleData) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@@ -198,13 +198,13 @@ public class ScaleDatabase extends SQLiteOpenHelper {
// selected scale data entry // selected scale data entry
cursorScaleDB = dbRead.query( cursorScaleDB = dbRead.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_ID + "=?", // The columns for the WHERE clause COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_ID + "=?", // The columns for the WHERE clause
new String[] {Integer.toString(userId), Long.toString(id)}, // The values for the WHERE clause new String[] {Integer.toString(userId), Long.toString(id)}, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
null, // The sort order null, // The sort order
"1" // Limit "1" // Limit
); );
@@ -217,13 +217,13 @@ public class ScaleDatabase extends SQLiteOpenHelper {
// previous scale entry // previous scale entry
cursorScaleDB = dbRead.query( cursorScaleDB = dbRead.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_DATE_TIME + "<? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_DATE_TIME + "<? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause
new String[] {Integer.toString(userId), formatDateTime.format(tupleScaleData[1].getDateTime())}, // The values for the WHERE clause new String[] {Integer.toString(userId), formatDateTime.format(tupleScaleData[1].getDateTime())}, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
COLUMN_NAME_DATE_TIME + " DESC", // The sort order COLUMN_NAME_DATE_TIME + " DESC", // The sort order
"1" // Limit "1" // Limit
); );
@@ -238,12 +238,12 @@ public class ScaleDatabase extends SQLiteOpenHelper {
// next scale data entry // next scale data entry
cursorScaleDB = dbRead.query( cursorScaleDB = dbRead.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_DATE_TIME + ">? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_DATE_TIME + ">? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause
new String[] {Integer.toString(userId), formatDateTime.format(tupleScaleData[1].getDateTime())}, // The values for the WHERE clause new String[] {Integer.toString(userId), formatDateTime.format(tupleScaleData[1].getDateTime())}, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
COLUMN_NAME_DATE_TIME, // The sort order COLUMN_NAME_DATE_TIME, // The sort order
"1" // Limit "1" // Limit
); );
@@ -311,13 +311,13 @@ public class ScaleDatabase extends SQLiteOpenHelper {
end_cal.add(Calendar.MONTH, 1); end_cal.add(Calendar.MONTH, 1);
Cursor cursorScaleDB = dbRead.query( Cursor cursorScaleDB = dbRead.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
COLUMN_NAME_DATE_TIME + " >= ? AND " + COLUMN_NAME_DATE_TIME + " < ? AND " + COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause COLUMN_NAME_DATE_TIME + " >= ? AND " + COLUMN_NAME_DATE_TIME + " < ? AND " + COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause
new String[]{formatDateTime.format(start_cal.getTime()), formatDateTime.format(end_cal.getTime()), Integer.toString(userId)}, // The values for the WHERE clause new String[]{formatDateTime.format(start_cal.getTime()), formatDateTime.format(end_cal.getTime()), Integer.toString(userId)}, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
sortOrder // The sort order sortOrder // The sort order
); );
cursorScaleDB.moveToFirst(); cursorScaleDB.moveToFirst();
@@ -345,13 +345,13 @@ public class ScaleDatabase extends SQLiteOpenHelper {
end_cal.set(year+1, Calendar.JANUARY, 1, 0, 0, 0); end_cal.set(year+1, Calendar.JANUARY, 1, 0, 0, 0);
Cursor cursorScaleDB = dbRead.query( Cursor cursorScaleDB = dbRead.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
COLUMN_NAME_DATE_TIME + " >= ? AND " + COLUMN_NAME_DATE_TIME + " < ? AND " + COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause COLUMN_NAME_DATE_TIME + " >= ? AND " + COLUMN_NAME_DATE_TIME + " < ? AND " + COLUMN_NAME_USER_ID + "=? AND " + COLUMN_NAME_ENABLE + "=1", // The columns for the WHERE clause
new String[]{formatDateTime.format(start_cal.getTime()), formatDateTime.format(end_cal.getTime()), Integer.toString(userId)}, // The values for the WHERE clause new String[]{formatDateTime.format(start_cal.getTime()), formatDateTime.format(end_cal.getTime()), Integer.toString(userId)}, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
sortOrder // The sort order sortOrder // The sort order
); );
cursorScaleDB.moveToFirst(); cursorScaleDB.moveToFirst();
@@ -367,8 +367,8 @@ public class ScaleDatabase extends SQLiteOpenHelper {
return scaleDataList; return scaleDataList;
} }
public ArrayList<ScaleData> getScaleDataList(int userId) { public ArrayList<ScaleData> getScaleDataList(int userId) {
ArrayList<ScaleData> scaleDataList = new ArrayList<ScaleData>(); ArrayList<ScaleData> scaleDataList = new ArrayList<ScaleData>();
try { try {
String sortOrder = COLUMN_NAME_DATE_TIME + " DESC"; String sortOrder = COLUMN_NAME_DATE_TIME + " DESC";
@@ -396,8 +396,8 @@ public class ScaleDatabase extends SQLiteOpenHelper {
Log.e("ScaleDatabase", "SQL exception occured while getting scale data list: " + ex.getMessage()); Log.e("ScaleDatabase", "SQL exception occured while getting scale data list: " + ex.getMessage());
} }
return scaleDataList; return scaleDataList;
} }
private ScaleData readAtCursor (Cursor cur) { private ScaleData readAtCursor (Cursor cur) {
@@ -421,7 +421,7 @@ public class ScaleDatabase extends SQLiteOpenHelper {
} catch (ParseException ex) { } catch (ParseException ex) {
Log.e("ScaleDatabase", "Can't parse the date time string: " + ex.getMessage()); Log.e("ScaleDatabase", "Can't parse the date time string: " + ex.getMessage());
} }
catch ( IllegalArgumentException ex) { catch (IllegalArgumentException ex) {
Log.e("ScaleDatabase", "Illegal argument while reading from scale database: " + ex.getMessage()); Log.e("ScaleDatabase", "Illegal argument while reading from scale database: " + ex.getMessage());
} }

View File

@@ -47,8 +47,8 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
private static final String COLUMN_NAME_GOAL_DATE = "goal_date"; private static final String COLUMN_NAME_GOAL_DATE = "goal_date";
private static final String SQL_CREATE_ENTRIES = private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" + "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME_USER_NAME + " TEXT," + COLUMN_NAME_USER_NAME + " TEXT," +
COLUMN_NAME_BIRTHDAY + " TEXT," + COLUMN_NAME_BIRTHDAY + " TEXT," +
COLUMN_NAME_BODY_HEIGHT + " INTEGER," + COLUMN_NAME_BODY_HEIGHT + " INTEGER," +
@@ -57,10 +57,10 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
COLUMN_NAME_INITIAL_WEIGHT + " REAL," + COLUMN_NAME_INITIAL_WEIGHT + " REAL," +
COLUMN_NAME_GOAL_WEIGHT + " REAL," + COLUMN_NAME_GOAL_WEIGHT + " REAL," +
COLUMN_NAME_GOAL_DATE + " TEXT" + COLUMN_NAME_GOAL_DATE + " TEXT" +
")"; ")";
private static final String SQL_DELETE_ENTRIES = private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TABLE_NAME; "DROP TABLE IF EXISTS " + TABLE_NAME;
private static String[] projection = { private static String[] projection = {
COLUMN_NAME_ID, COLUMN_NAME_ID,
@@ -76,17 +76,17 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
private SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US); private SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
public ScaleUserDatabase(Context context) { public ScaleUserDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION); super(context, DATABASE_NAME, null, DATABASE_VERSION);
} }
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES); db.execSQL(SQL_CREATE_ENTRIES);
} }
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) { if (oldVersion == 1 && newVersion == 2) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_GENDER + " INTEGER DEFAULT 0"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_GENDER + " INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_GOAL_WEIGHT + " REAL DEFAULT 0"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_GOAL_WEIGHT + " REAL DEFAULT 0");
@@ -96,16 +96,16 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
if (oldVersion == 2 && newVersion == 3) { if (oldVersion == 2 && newVersion == 3) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_INITIAL_WEIGHT + " REAL DEFAULT 0"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + COLUMN_NAME_INITIAL_WEIGHT + " REAL DEFAULT 0");
} }
} }
public void clearDatabase() { public void clearDatabase() {
SQLiteDatabase db = getWritableDatabase(); SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, null, null); db.delete(TABLE_NAME, null, null);
} }
public boolean insertEntry(ScaleUser scaleUser) { public boolean insertEntry(ScaleUser scaleUser) {
SQLiteDatabase db = getWritableDatabase(); SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(COLUMN_NAME_USER_NAME, scaleUser.user_name); values.put(COLUMN_NAME_USER_NAME, scaleUser.user_name);
@@ -128,7 +128,7 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
} }
return true; return true;
} }
public void deleteEntry(int id) { public void deleteEntry(int id) {
SQLiteDatabase db = getWritableDatabase(); SQLiteDatabase db = getWritableDatabase();
@@ -158,13 +158,13 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
SQLiteDatabase db = getReadableDatabase(); SQLiteDatabase db = getReadableDatabase();
Cursor cursorScaleDB = db.query( Cursor cursorScaleDB = db.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
COLUMN_NAME_ID + "=?", // The columns for the WHERE clause COLUMN_NAME_ID + "=?", // The columns for the WHERE clause
new String[] {Integer.toString(id)}, // The values for the WHERE clause new String[] {Integer.toString(id)}, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
null // The sort order null // The sort order
); );
cursorScaleDB.moveToFirst(); cursorScaleDB.moveToFirst();
@@ -176,34 +176,34 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
return scaleUser; return scaleUser;
} }
public ArrayList<ScaleUser> getScaleUserList() { public ArrayList<ScaleUser> getScaleUserList() {
SQLiteDatabase db = getReadableDatabase(); SQLiteDatabase db = getReadableDatabase();
ArrayList<ScaleUser> scaleUserDBEntries = new ArrayList<ScaleUser>(); ArrayList<ScaleUser> scaleUserDBEntries = new ArrayList<ScaleUser>();
String sortOrder = COLUMN_NAME_ID + " ASC"; String sortOrder = COLUMN_NAME_ID + " ASC";
Cursor cursorScaleDB = db.query( Cursor cursorScaleDB = db.query(
TABLE_NAME, // The table to query TABLE_NAME, // The table to query
projection, // The columns to return projection, // The columns to return
null, // The columns for the WHERE clause null, // The columns for the WHERE clause
null, // The values for the WHERE clause null, // The values for the WHERE clause
null, // don't group the rows null, // don't group the rows
null, // don't filter by row groups null, // don't filter by row groups
sortOrder // The sort order sortOrder // The sort order
); );
cursorScaleDB.moveToFirst(); cursorScaleDB.moveToFirst();
while (!cursorScaleDB.isAfterLast()) { while (!cursorScaleDB.isAfterLast()) {
scaleUserDBEntries.add(readAtCursor(cursorScaleDB)); scaleUserDBEntries.add(readAtCursor(cursorScaleDB));
cursorScaleDB.moveToNext(); cursorScaleDB.moveToNext();
} }
cursorScaleDB.close(); cursorScaleDB.close();
return scaleUserDBEntries; return scaleUserDBEntries;
} }
private ScaleUser readAtCursor (Cursor cur) { private ScaleUser readAtCursor (Cursor cur) {
ScaleUser scaleUser = new ScaleUser(); ScaleUser scaleUser = new ScaleUser();
@@ -227,7 +227,7 @@ public class ScaleUserDatabase extends SQLiteOpenHelper {
} catch (ParseException ex) { } catch (ParseException ex) {
Log.e("ScaleDatabase", "Can't parse the date time string: " + ex.getMessage()); Log.e("ScaleDatabase", "Can't parse the date time string: " + ex.getMessage());
} }
catch ( IllegalArgumentException ex) { catch (IllegalArgumentException ex) {
Log.e("ScaleDatabase", "Illegal argument while reading from scale database: " + ex.getMessage()); Log.e("ScaleDatabase", "Illegal argument while reading from scale database: " + ex.getMessage());
} }

View File

@@ -194,7 +194,7 @@ public class ScaleData {
} }
public float getWHtR(int body_height) { public float getWHtR(int body_height) {
return waist / (float)body_height ; return waist / (float)body_height;
} }
public float getWHR() { public float getWHR() {
@@ -205,9 +205,9 @@ public class ScaleData {
return waist / hip; return waist / hip;
} }
@Override @Override
public String toString() public String toString()
{ {
return "ID : " + id + " USER_ID: " + user_id + " DATE_TIME: " + date_time.toString() + " WEIGHT: " + weight + " FAT: " + fat + " WATER: " + water + " MUSCLE: " + muscle + " LBW: " + lbw + " WAIST: " + waist + " HIP: " + hip + " BONE: " + bone + " COMMENT: " + comment; return "ID : " + id + " USER_ID: " + user_id + " DATE_TIME: " + date_time.toString() + " WEIGHT: " + weight + " FAT: " + fat + " WATER: " + water + " MUSCLE: " + muscle + " LBW: " + lbw + " WAIST: " + waist + " HIP: " + hip + " BONE: " + bone + " COMMENT: " + comment;
} }
} }

View File

@@ -24,11 +24,11 @@ public class ScaleUser {
private static float KG_LB = 2.20462f; private static float KG_LB = 2.20462f;
private static float KG_ST = 0.157473f; private static float KG_ST = 0.157473f;
public int id; public int id;
public String user_name; public String user_name;
public Date birthday; public Date birthday;
public int body_height; public int body_height;
public int scale_unit; public int scale_unit;
public int gender; public int gender;
private float initial_weight; private float initial_weight;
public float goal_weight; public float goal_weight;
@@ -106,9 +106,9 @@ public class ScaleUser {
return converted_weight; return converted_weight;
} }
@Override @Override
public String toString() public String toString()
{ {
return "ID : " + id + " NAME: " + user_name + " BIRTHDAY: " + birthday.toString() + " BODY_HEIGHT: " + body_height + " SCALE_UNIT: " + UNIT_STRING[scale_unit] + " GENDER " + gender + " INITIAL WEIGHT " + initial_weight + " GOAL WEIGHT " + goal_weight + " GOAL DATE " + goal_date.toString(); return "ID : " + id + " NAME: " + user_name + " BIRTHDAY: " + birthday.toString() + " BODY_HEIGHT: " + body_height + " SCALE_UNIT: " + UNIT_STRING[scale_unit] + " GENDER " + gender + " INITIAL WEIGHT " + initial_weight + " GOAL WEIGHT " + goal_weight + " GOAL DATE " + goal_date.toString();
} }
} }

View File

@@ -53,69 +53,69 @@ import java.util.Locale;
public class MainActivity extends ActionBarActivity implements public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener { ActionBar.TabListener {
/** /**
* The {@link android.support.v4.view.PagerAdapter} that will provide * The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {@link FragmentPagerAdapter} * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this * derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a * becomes too memory intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}. * {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/ */
private SectionsPagerAdapter mSectionsPagerAdapter; private SectionsPagerAdapter mSectionsPagerAdapter;
private static boolean firstAppStart = true; private static boolean firstAppStart = true;
private static int bluetoothStatusIcon = R.drawable.ic_bluetooth_disabled; private static int bluetoothStatusIcon = R.drawable.ic_bluetooth_disabled;
private static MenuItem bluetoothStatus; private static MenuItem bluetoothStatus;
/** /**
* The {@link ViewPager} that will host the section contents. * The {@link ViewPager} that will host the section contents.
*/ */
private ViewPager mViewPager; private ViewPager mViewPager;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Set up the action bar. // Set up the action bar.
final ActionBar actionBar = getSupportActionBar(); final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setLogo(R.drawable.ic_launcher_openscale); actionBar.setLogo(R.drawable.ic_launcher_openscale);
// Create the adapter that will return a fragment for each of the three // Create the adapter that will return a fragment for each of the three
// primary sections of the activity. // primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter. // Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding // When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have // tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab. // a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override @Override
public void onPageSelected(int position) { public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position); actionBar.setSelectedNavigationItem(position);
} }
}); });
// For each of the sections in the app, add a tab to the action bar. // For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by // Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements // the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when // the TabListener interface, as the callback (listener) for when
// this tab is selected. // this tab is selected.
actionBar.addTab(actionBar.newTab() actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i)) .setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this)); .setTabListener(this));
} }
if (prefs.getBoolean("firstStart", true)) { if (prefs.getBoolean("firstStart", true)) {
@@ -125,210 +125,210 @@ public class MainActivity extends ActionBarActivity implements
prefs.edit().putBoolean("firstStart", false).commit(); prefs.edit().putBoolean("firstStart", false).commit();
} }
} }
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present. // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu); getMenuInflater().inflate(R.menu.main, menu);
bluetoothStatus = menu.findItem(R.id.action_bluetooth_status); bluetoothStatus = menu.findItem(R.id.action_bluetooth_status);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Just search for a bluetooth device just once at the start of the app and if start preference enabled // Just search for a bluetooth device just once at the start of the app and if start preference enabled
if (firstAppStart && prefs.getBoolean("btEnable", false)) { if (firstAppStart && prefs.getBoolean("btEnable", false)) {
invokeSearchBluetoothDevice(); invokeSearchBluetoothDevice();
firstAppStart = false; firstAppStart = false;
} else { } else {
// Set current bluetooth status icon while e.g. orientation changes // Set current bluetooth status icon while e.g. orientation changes
setBluetoothStatusIcon(bluetoothStatusIcon); setBluetoothStatusIcon(bluetoothStatusIcon);
} }
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); int id = item.getItemId();
if (id == R.id.action_general_settings) { if (id == R.id.action_general_settings) {
Intent intent = new Intent(this, SettingsActivity.class); Intent intent = new Intent(this, SettingsActivity.class);
startActivityForResult(intent, 1); startActivityForResult(intent, 1);
return true; return true;
} }
if (id == R.id.action_bluetooth_status) { if (id == R.id.action_bluetooth_status) {
invokeSearchBluetoothDevice(); invokeSearchBluetoothDevice();
return true; return true;
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
private void invokeSearchBluetoothDevice() { private void invokeSearchBluetoothDevice() {
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter btAdapter = bluetoothManager.getAdapter(); BluetoothAdapter btAdapter = bluetoothManager.getAdapter();
if (btAdapter == null || !btAdapter.isEnabled()) { if (btAdapter == null || !btAdapter.isEnabled()) {
setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled); setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled);
Toast.makeText(getApplicationContext(), "Bluetooth " + getResources().getString(R.string.info_is_not_enable), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "Bluetooth " + getResources().getString(R.string.info_is_not_enable), Toast.LENGTH_SHORT).show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1); startActivityForResult(enableBtIntent, 1);
return; return;
} }
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String deviceName = prefs.getString("btDeviceName", "MI_SCALE"); String deviceName = prefs.getString("btDeviceName", "MI_SCALE");
// Check if Bluetooth 4.x is available // Check if Bluetooth 4.x is available
if (deviceName != "openScale_MCU") { if (deviceName != "openScale_MCU") {
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled); setBluetoothStatusIcon(R.drawable.ic_bluetooth_disabled);
Toast.makeText(getApplicationContext(), "Bluetooth 4.x " + getResources().getString(R.string.info_is_not_available), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "Bluetooth 4.x " + getResources().getString(R.string.info_is_not_available), Toast.LENGTH_SHORT).show();
return; return;
} }
} }
Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_try_connection) + " " + deviceName, Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_try_connection) + " " + deviceName, Toast.LENGTH_SHORT).show();
setBluetoothStatusIcon(R.drawable.ic_bluetooth_searching); setBluetoothStatusIcon(R.drawable.ic_bluetooth_searching);
OpenScale.getInstance(getApplicationContext()).stopSearchingForBluetooth(); OpenScale.getInstance(getApplicationContext()).stopSearchingForBluetooth();
if (!OpenScale.getInstance(getApplicationContext()).startSearchingForBluetooth(deviceName, callbackBtHandler)) { if (!OpenScale.getInstance(getApplicationContext()).startSearchingForBluetooth(deviceName, callbackBtHandler)) {
Toast.makeText(getApplicationContext(), deviceName + " " + getResources().getString(R.string.label_bt_device_no_support), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), deviceName + " " + getResources().getString(R.string.label_bt_device_no_support), Toast.LENGTH_SHORT).show();
} }
} }
private final Handler callbackBtHandler = new Handler() { private final Handler callbackBtHandler = new Handler() {
@Override @Override
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
BluetoothCommunication.BT_STATUS_CODE btStatusCode = BluetoothCommunication.BT_STATUS_CODE.values()[msg.what]; BluetoothCommunication.BT_STATUS_CODE btStatusCode = BluetoothCommunication.BT_STATUS_CODE.values()[msg.what];
switch (btStatusCode) { switch (btStatusCode) {
case BT_RETRIEVE_SCALE_DATA: case BT_RETRIEVE_SCALE_DATA:
setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_success); setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_success);
ScaleData scaleBtData = (ScaleData) msg.obj; ScaleData scaleBtData = (ScaleData) msg.obj;
scaleBtData.setConvertedWeight(scaleBtData.getWeight(), OpenScale.getInstance(getApplicationContext()).getSelectedScaleUser().scale_unit); scaleBtData.setConvertedWeight(scaleBtData.getWeight(), OpenScale.getInstance(getApplicationContext()).getSelectedScaleUser().scale_unit);
OpenScale.getInstance(getApplicationContext()).addScaleData(scaleBtData); OpenScale.getInstance(getApplicationContext()).addScaleData(scaleBtData);
break; break;
case BT_INIT_PROCESS: case BT_INIT_PROCESS:
setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_success); setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_success);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_init), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_init), Toast.LENGTH_SHORT).show();
Log.d("OpenScale", "Bluetooth initializing"); Log.d("OpenScale", "Bluetooth initializing");
break; break;
case BT_CONNECTION_LOST: case BT_CONNECTION_LOST:
setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_lost); setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_lost);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_connection_lost), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_connection_lost), Toast.LENGTH_SHORT).show();
Log.d("OpenScale", "Bluetooth connection lost"); Log.d("OpenScale", "Bluetooth connection lost");
break; break;
case BT_NO_DEVICE_FOUND: case BT_NO_DEVICE_FOUND:
setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_lost); setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_lost);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_no_device), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_no_device), Toast.LENGTH_SHORT).show();
Log.d("OpenScale", "No Bluetooth device found"); Log.d("OpenScale", "No Bluetooth device found");
break; break;
case BT_CONNECTION_ESTABLISHED: case BT_CONNECTION_ESTABLISHED:
setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_success); setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_success);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_connection_successful), Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_connection_successful), Toast.LENGTH_SHORT).show();
Log.d("OpenScale", "Bluetooth connection successful established"); Log.d("OpenScale", "Bluetooth connection successful established");
break; break;
case BT_UNEXPECTED_ERROR: case BT_UNEXPECTED_ERROR:
setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_lost); setBluetoothStatusIcon(R.drawable.ic_bluetooth_connection_lost);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_connection_error) + ": " + msg.obj, Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), getResources().getString(R.string.info_bluetooth_connection_error) + ": " + msg.obj, Toast.LENGTH_SHORT).show();
Log.e("OpenScale", "Bluetooth unexpected error: " + msg.obj); Log.e("OpenScale", "Bluetooth unexpected error: " + msg.obj);
break; break;
case BT_SCALE_MESSAGE: case BT_SCALE_MESSAGE:
String toastMessage = String.format(getResources().getString(msg.arg1), msg.obj); String toastMessage = String.format(getResources().getString(msg.arg1), msg.obj);
Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_LONG).show();
break; break;
} }
} }
}; };
private void setBluetoothStatusIcon(int iconRessource) { private void setBluetoothStatusIcon(int iconRessource) {
bluetoothStatusIcon = iconRessource; bluetoothStatusIcon = iconRessource;
bluetoothStatus.setIcon(getResources().getDrawable(bluetoothStatusIcon)); bluetoothStatus.setIcon(getResources().getDrawable(bluetoothStatusIcon));
} }
@Override @Override
public void onTabSelected(ActionBar.Tab tab, public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) { FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in // When the given tab is selected, switch to the corresponding page in
// the ViewPager. // the ViewPager.
mViewPager.setCurrentItem(tab.getPosition()); mViewPager.setCurrentItem(tab.getPosition());
} }
@Override @Override
public void onTabUnselected(ActionBar.Tab tab, public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) { FragmentTransaction fragmentTransaction) {
} }
@Override @Override
public void onTabReselected(ActionBar.Tab tab, public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) { FragmentTransaction fragmentTransaction) {
} }
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) { if (requestCode == 1) {
mSectionsPagerAdapter.notifyDataSetChanged(); mSectionsPagerAdapter.notifyDataSetChanged();
} }
} }
/** /**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages. * one of the sections/tabs/pages.
*/ */
public class SectionsPagerAdapter extends FragmentPagerAdapter { public class SectionsPagerAdapter extends FragmentPagerAdapter {
private OverviewFragment overviewFrag; private OverviewFragment overviewFrag;
private GraphFragment graphFrag; private GraphFragment graphFrag;
private TableFragment tableFrag; private TableFragment tableFrag;
private StatisticsFragment statisticsFrag; private StatisticsFragment statisticsFrag;
public SectionsPagerAdapter(FragmentManager fm) { public SectionsPagerAdapter(FragmentManager fm) {
super(fm); super(fm);
overviewFrag = new OverviewFragment(); overviewFrag = new OverviewFragment();
graphFrag = new GraphFragment(); graphFrag = new GraphFragment();
tableFrag = new TableFragment(); tableFrag = new TableFragment();
statisticsFrag = new StatisticsFragment(); statisticsFrag = new StatisticsFragment();
} }
@Override @Override
public Fragment getItem(int position) { public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page. // getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class // Return a PlaceholderFragment (defined as a static inner class
// below). // below).
switch (position) { switch (position) {
case 0: case 0:
return overviewFrag; return overviewFrag;
case 1: case 1:
return graphFrag; return graphFrag;
case 2: case 2:
return tableFrag; return tableFrag;
case 3: case 3:
return statisticsFrag; return statisticsFrag;
} }
return null; return null;
} }
@Override @Override
public int getCount() { public int getCount() {
return 4; return 4;
} }
@Override @Override
public CharSequence getPageTitle(int position) { public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault(); Locale l = Locale.getDefault();
switch (position) { switch (position) {
case 0: case 0:
return getString(R.string.title_overview).toUpperCase(l); return getString(R.string.title_overview).toUpperCase(l);
case 1: case 1:
@@ -337,23 +337,23 @@ public class MainActivity extends ActionBarActivity implements
return getString(R.string.title_table).toUpperCase(l); return getString(R.string.title_table).toUpperCase(l);
case 3: case 3:
return getString(R.string.title_statistics).toUpperCase(l); return getString(R.string.title_statistics).toUpperCase(l);
} }
return null; return null;
} }
@Override @Override
public int getItemPosition(Object object) { public int getItemPosition(Object object) {
return POSITION_NONE; return POSITION_NONE;
} }
@Override @Override
public void notifyDataSetChanged() { public void notifyDataSetChanged() {
super.notifyDataSetChanged(); super.notifyDataSetChanged();
tableFrag = new TableFragment(); tableFrag = new TableFragment();
graphFrag = new GraphFragment(); graphFrag = new GraphFragment();
overviewFrag = new OverviewFragment(); overviewFrag = new OverviewFragment();
statisticsFrag = new StatisticsFragment(); statisticsFrag = new StatisticsFragment();
} }
} }
} }

View File

@@ -92,15 +92,15 @@ public class DataEntryActivity extends Activity {
private long id; private long id;
private Context context; private Context context;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dataentry); setContentView(R.layout.activity_dataentry);
context = this; context = this;
tableLayoutDataEntry = (TableLayout) findViewById(R.id.tableLayoutDataEntry); tableLayoutDataEntry = (TableLayout) findViewById(R.id.tableLayoutDataEntry);
@@ -145,8 +145,8 @@ public class DataEntryActivity extends Activity {
txtDataNr = (TextView) findViewById(R.id.txtDataNr); txtDataNr = (TextView) findViewById(R.id.txtDataNr);
btnAdd = (Button) findViewById(R.id.btnAdd); btnAdd = (Button) findViewById(R.id.btnAdd);
btnOk = (Button) findViewById(R.id.btnOk); btnOk = (Button) findViewById(R.id.btnOk);
btnCancel = (Button) findViewById(R.id.btnCancel); btnCancel = (Button) findViewById(R.id.btnCancel);
btnLeft = (Button) findViewById(R.id.btnLeft); btnLeft = (Button) findViewById(R.id.btnLeft);
btnRight = (Button) findViewById(R.id.btnRight); btnRight = (Button) findViewById(R.id.btnRight);
@@ -164,7 +164,7 @@ public class DataEntryActivity extends Activity {
expandButton.setOnClickListener(new onClickListenerToggleButton()); expandButton.setOnClickListener(new onClickListenerToggleButton());
updateOnView(); updateOnView();
} }
private void updateOnView() private void updateOnView()

View File

@@ -45,12 +45,12 @@ public class UserSettingsActivity extends Activity {
public static final int ADD_USER_REQUEST = 0; public static final int ADD_USER_REQUEST = 0;
public static final int EDIT_USER_REQUEST = 1; public static final int EDIT_USER_REQUEST = 1;
private Date birthday = new Date(); private Date birthday = new Date();
private Date goal_date = new Date(); private Date goal_date = new Date();
private EditText txtUserName; private EditText txtUserName;
private EditText txtBodyHeight; private EditText txtBodyHeight;
private EditText txtBirthday; private EditText txtBirthday;
private EditText txtInitialWeight; private EditText txtInitialWeight;
private EditText txtGoalWeight; private EditText txtGoalWeight;
private EditText txtGoalDate; private EditText txtGoalDate;
@@ -61,18 +61,18 @@ public class UserSettingsActivity extends Activity {
private Button btnCancel; private Button btnCancel;
private Button btnDelete; private Button btnDelete;
private DateFormat dateFormat = DateFormat.getDateInstance(); private DateFormat dateFormat = DateFormat.getDateInstance();
private Context context; private Context context;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usersettings); setContentView(R.layout.activity_usersettings);
context = this; context = this;
txtUserName = (EditText) findViewById(R.id.txtUserName); txtUserName = (EditText) findViewById(R.id.txtUserName);
txtBodyHeight = (EditText) findViewById(R.id.txtBodyHeight); txtBodyHeight = (EditText) findViewById(R.id.txtBodyHeight);
radioScaleUnit = (RadioGroup) findViewById(R.id.groupScaleUnit); radioScaleUnit = (RadioGroup) findViewById(R.id.groupScaleUnit);
radioGender = (RadioGroup) findViewById(R.id.groupGender); radioGender = (RadioGroup) findViewById(R.id.groupGender);
txtInitialWeight = (EditText) findViewById(R.id.txtInitialWeight); txtInitialWeight = (EditText) findViewById(R.id.txtInitialWeight);
@@ -125,7 +125,7 @@ public class UserSettingsActivity extends Activity {
btnOk.setText(getResources().getString(R.string.label_add)); btnOk.setText(getResources().getString(R.string.label_add));
btnDelete.setVisibility(View.GONE); btnDelete.setVisibility(View.GONE);
} }
} }
private void editMode() private void editMode()
{ {
@@ -173,26 +173,22 @@ public class UserSettingsActivity extends Activity {
{ {
boolean validate = true; boolean validate = true;
if( txtUserName.getText().toString().length() == 0 ) if (txtUserName.getText().toString().length() == 0) {
{
txtUserName.setError(getResources().getString(R.string.error_user_name_required)); txtUserName.setError(getResources().getString(R.string.error_user_name_required));
validate = false; validate = false;
} }
if( txtBodyHeight.getText().toString().length() == 0 ) if (txtBodyHeight.getText().toString().length() == 0) {
{
txtBodyHeight.setError(getResources().getString(R.string.error_body_height_required)); txtBodyHeight.setError(getResources().getString(R.string.error_body_height_required));
validate = false; validate = false;
} }
if( txtInitialWeight.getText().toString().length() == 0 ) if (txtInitialWeight.getText().toString().length() == 0) {
{
txtInitialWeight.setError(getResources().getString(R.string.error_initial_weight_required)); txtInitialWeight.setError(getResources().getString(R.string.error_initial_weight_required));
validate = false; validate = false;
} }
if( txtGoalWeight.getText().toString().length() == 0 ) if (txtGoalWeight.getText().toString().length() == 0) {
{
txtGoalWeight.setError(getResources().getString(R.string.error_goal_weight_required)); txtGoalWeight.setError(getResources().getString(R.string.error_goal_weight_required));
validate = false; validate = false;
} }

View File

@@ -21,5 +21,5 @@ import com.health.openscale.core.datatypes.ScaleData;
import java.util.ArrayList; import java.util.ArrayList;
public interface FragmentUpdateListener { public interface FragmentUpdateListener {
public void updateOnView(ArrayList<ScaleData> scaleDataList); public void updateOnView(ArrayList<ScaleData> scaleDataList);
} }

View File

@@ -64,8 +64,8 @@ import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView; import lecho.lib.hellocharts.view.LineChartView;
public class GraphFragment extends Fragment implements FragmentUpdateListener { public class GraphFragment extends Fragment implements FragmentUpdateListener {
private View graphView; private View graphView;
private LineChartView chartBottom; private LineChartView chartBottom;
private ColumnChartView chartTop; private ColumnChartView chartTop;
private Viewport defaultTopViewport; private Viewport defaultTopViewport;
private TextView txtYear; private TextView txtYear;
@@ -88,17 +88,17 @@ public class GraphFragment extends Fragment implements FragmentUpdateListener {
private ArrayList<ScaleData> scaleDataList; private ArrayList<ScaleData> scaleDataList;
private ArrayList<ScaleData> pointIndexScaleDataList; private ArrayList<ScaleData> pointIndexScaleDataList;
public GraphFragment() { public GraphFragment() {
calYears = Calendar.getInstance(); calYears = Calendar.getInstance();
calLastSelected = Calendar.getInstance(); calLastSelected = Calendar.getInstance();
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{ {
graphView = inflater.inflate(R.layout.fragment_graph, container, false); graphView = inflater.inflate(R.layout.fragment_graph, container, false);
chartBottom = (LineChartView) graphView.findViewById(R.id.chart_bottom); chartBottom = (LineChartView) graphView.findViewById(R.id.chart_bottom);
chartTop = (ColumnChartView) graphView.findViewById(R.id.chart_top); chartTop = (ColumnChartView) graphView.findViewById(R.id.chart_top);
chartBottom.setOnTouchListener(new chartBottomListener()); chartBottom.setOnTouchListener(new chartBottomListener());
@@ -131,35 +131,35 @@ public class GraphFragment extends Fragment implements FragmentUpdateListener {
prefs = PreferenceManager.getDefaultSharedPreferences(graphView.getContext()); prefs = PreferenceManager.getDefaultSharedPreferences(graphView.getContext());
if(!prefs.getBoolean("weightEnable", true)) { if (!prefs.getBoolean("weightEnable", true)) {
diagramWeight.setVisibility(View.GONE); diagramWeight.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("fatEnable", true)) { if (!prefs.getBoolean("fatEnable", true)) {
diagramFat.setVisibility(View.GONE); diagramFat.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("waterEnable", true)) { if (!prefs.getBoolean("waterEnable", true)) {
diagramWater.setVisibility(View.GONE); diagramWater.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("muscleEnable", true)) { if (!prefs.getBoolean("muscleEnable", true)) {
diagramMuscle.setVisibility(View.GONE); diagramMuscle.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("lbwEnable", false)) { if (!prefs.getBoolean("lbwEnable", false)) {
diagramLBW.setVisibility(View.GONE); diagramLBW.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("boneEnable", false)) { if (!prefs.getBoolean("boneEnable", false)) {
diagramBone.setVisibility(View.GONE); diagramBone.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("waistEnable", false)) { if (!prefs.getBoolean("waistEnable", false)) {
diagramWaist.setVisibility(View.GONE); diagramWaist.setVisibility(View.GONE);
} }
if(!prefs.getBoolean("hipEnable", false)) { if (!prefs.getBoolean("hipEnable", false)) {
diagramHip.setVisibility(View.GONE); diagramHip.setVisibility(View.GONE);
} }
@@ -182,14 +182,14 @@ public class GraphFragment extends Fragment implements FragmentUpdateListener {
openScale = OpenScale.getInstance(getContext()); openScale = OpenScale.getInstance(getContext());
openScale.registerFragment(this); openScale.registerFragment(this);
return graphView; return graphView;
} }
@Override @Override
public void updateOnView(ArrayList<ScaleData> scaleDataList) public void updateOnView(ArrayList<ScaleData> scaleDataList)
{ {
generateGraphs(); generateGraphs();
} }
/** /**
* Add a point to a point value stack. * Add a point to a point value stack.
@@ -258,8 +258,7 @@ public class GraphFragment extends Fragment implements FragmentUpdateListener {
pointIndexScaleDataList = new ArrayList<>(); pointIndexScaleDataList = new ArrayList<>();
for(ScaleData scaleEntry: scaleDataList) for (ScaleData scaleEntry: scaleDataList) {
{
calDB.setTime(scaleEntry.getDateTime()); calDB.setTime(scaleEntry.getDateTime());
if (addPointValue(valuesWeight, calDB.get(field), scaleEntry.getConvertedWeight(openScale.getSelectedScaleUser().scale_unit))) { if (addPointValue(valuesWeight, calDB.get(field), scaleEntry.getConvertedWeight(openScale.getSelectedScaleUser().scale_unit))) {
@@ -317,63 +316,63 @@ public class GraphFragment extends Fragment implements FragmentUpdateListener {
setHasPoints(prefs.getBoolean("pointsEnable", true)). setHasPoints(prefs.getBoolean("pointsEnable", true)).
setFormatter(new SimpleLineChartValueFormatter(1)); setFormatter(new SimpleLineChartValueFormatter(1));
if(prefs.getBoolean("weightEnable", true) && prefs.getBoolean(String.valueOf(diagramWeight.getId()), true)) { if (prefs.getBoolean("weightEnable", true) && prefs.getBoolean(String.valueOf(diagramWeight.getId()), true)) {
lines.add(lineWeight); lines.add(lineWeight);
diagramWeight.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_VIOLET)); diagramWeight.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_VIOLET));
} else { } else {
diagramWeight.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramWeight.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("fatEnable", true) && prefs.getBoolean(String.valueOf(diagramFat.getId()), true)) { if (prefs.getBoolean("fatEnable", true) && prefs.getBoolean(String.valueOf(diagramFat.getId()), true)) {
lines.add(lineFat); lines.add(lineFat);
diagramFat.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_ORANGE)); diagramFat.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_ORANGE));
} else { } else {
diagramFat.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramFat.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("waterEnable", true) && prefs.getBoolean(String.valueOf(diagramWater.getId()), true)) { if (prefs.getBoolean("waterEnable", true) && prefs.getBoolean(String.valueOf(diagramWater.getId()), true)) {
lines.add(lineWater); lines.add(lineWater);
diagramWater.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_BLUE)); diagramWater.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_BLUE));
} else { } else {
diagramWater.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramWater.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("muscleEnable", true) && prefs.getBoolean(String.valueOf(diagramMuscle.getId()), true)) { if (prefs.getBoolean("muscleEnable", true) && prefs.getBoolean(String.valueOf(diagramMuscle.getId()), true)) {
lines.add(lineMuscle); lines.add(lineMuscle);
diagramMuscle.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_GREEN)); diagramMuscle.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_GREEN));
} else { } else {
diagramMuscle.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramMuscle.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("lbwEnable", false) && prefs.getBoolean(String.valueOf(diagramLBW.getId()), true)) { if (prefs.getBoolean("lbwEnable", false) && prefs.getBoolean(String.valueOf(diagramLBW.getId()), true)) {
lines.add(lineLBW); lines.add(lineLBW);
diagramLBW.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#cc0099"))); diagramLBW.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#cc0099")));
} else { } else {
diagramLBW.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramLBW.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("waistEnable", false) && prefs.getBoolean(String.valueOf(diagramWaist.getId()), true)) { if (prefs.getBoolean("waistEnable", false) && prefs.getBoolean(String.valueOf(diagramWaist.getId()), true)) {
lines.add(lineWaist); lines.add(lineWaist);
diagramWaist.setBackgroundTintList(ColorStateList.valueOf(Color.MAGENTA)); diagramWaist.setBackgroundTintList(ColorStateList.valueOf(Color.MAGENTA));
} else { } else {
diagramWaist.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramWaist.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("hipEnable", false) && prefs.getBoolean(String.valueOf(diagramHip.getId()), true)) { if (prefs.getBoolean("hipEnable", false) && prefs.getBoolean(String.valueOf(diagramHip.getId()), true)) {
lines.add(lineHip); lines.add(lineHip);
diagramHip.setBackgroundTintList(ColorStateList.valueOf(Color.YELLOW)); diagramHip.setBackgroundTintList(ColorStateList.valueOf(Color.YELLOW));
} else { } else {
diagramHip.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramHip.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean("boneEnable", false) && prefs.getBoolean(String.valueOf(diagramBone.getId()), true)) { if (prefs.getBoolean("boneEnable", false) && prefs.getBoolean(String.valueOf(diagramBone.getId()), true)) {
lines.add(lineBone); lines.add(lineBone);
diagramBone.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#00cc9e"))); diagramBone.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#00cc9e")));
} else { } else {
diagramBone.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); diagramBone.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
} }
if(prefs.getBoolean(String.valueOf(enableMonth.getId()), true)) { if (prefs.getBoolean(String.valueOf(enableMonth.getId()), true)) {
enableMonth.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_BLUE)); enableMonth.setBackgroundTintList(ColorStateList.valueOf(ChartUtils.COLOR_BLUE));
} else { } else {
enableMonth.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3"))); enableMonth.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#d3d3d3")));
@@ -414,7 +413,7 @@ public class GraphFragment extends Fragment implements FragmentUpdateListener {
if (prefs.getBoolean("regressionLine", false)) { if (prefs.getBoolean("regressionLine", false)) {
PolynomialFitter polyFitter = new PolynomialFitter(Integer.parseInt(prefs.getString("regressionLineOrder", "1"))); PolynomialFitter polyFitter = new PolynomialFitter(Integer.parseInt(prefs.getString("regressionLineOrder", "1")));
for(PointValue weightValue : valuesWeight) { for (PointValue weightValue : valuesWeight) {
polyFitter.addPoint(weightValue.getX(), weightValue.getY()); polyFitter.addPoint(weightValue.getX(), weightValue.getY());
} }

View File

@@ -217,7 +217,7 @@ public class OverviewFragment extends Fragment implements FragmentUpdateListener
int posUser = 0; int posUser = 0;
int pos = 0; int pos = 0;
for(ScaleUser scaleUser :scaleUserList) { for (ScaleUser scaleUser :scaleUserList) {
spinUserAdapter.add(scaleUser.user_name); spinUserAdapter.add(scaleUser.user_name);
if (scaleUser.id == currentScaleUser.id) { if (scaleUser.id == currentScaleUser.id) {
@@ -328,35 +328,35 @@ public class OverviewFragment extends Fragment implements FragmentUpdateListener
setHasPoints(prefs.getBoolean("pointsEnable", true)). setHasPoints(prefs.getBoolean("pointsEnable", true)).
setFormatter(new SimpleLineChartValueFormatter(1)); setFormatter(new SimpleLineChartValueFormatter(1));
if(prefs.getBoolean("weightEnable", true)) { if (prefs.getBoolean("weightEnable", true)) {
lines.add(lineWeight); lines.add(lineWeight);
} }
if(prefs.getBoolean("fatEnable", true)) { if (prefs.getBoolean("fatEnable", true)) {
lines.add(lineFat); lines.add(lineFat);
} }
if(prefs.getBoolean("waterEnable", true)) { if (prefs.getBoolean("waterEnable", true)) {
lines.add(lineWater); lines.add(lineWater);
} }
if(prefs.getBoolean("muscleEnable", true)) { if (prefs.getBoolean("muscleEnable", true)) {
lines.add(lineMuscle); lines.add(lineMuscle);
} }
if(prefs.getBoolean("lbwEnable", false)) { if (prefs.getBoolean("lbwEnable", false)) {
lines.add(lineLBW); lines.add(lineLBW);
} }
if(prefs.getBoolean("waistEnable", false)) { if (prefs.getBoolean("waistEnable", false)) {
lines.add(lineWaist); lines.add(lineWaist);
} }
if(prefs.getBoolean("hipEnable", false)) { if (prefs.getBoolean("hipEnable", false)) {
lines.add(lineHip); lines.add(lineHip);
} }
if(prefs.getBoolean("boneEnable", false)) { if (prefs.getBoolean("boneEnable", false)) {
lines.add(lineBone); lines.add(lineBone);
} }
@@ -427,11 +427,11 @@ public class OverviewFragment extends Fragment implements FragmentUpdateListener
return startDate.get(Calendar.DAY_OF_YEAR) - endDate.get(Calendar.DAY_OF_YEAR); return startDate.get(Calendar.DAY_OF_YEAR) - endDate.get(Calendar.DAY_OF_YEAR);
} }
public void btnOnClickInsertData() public void btnOnClickInsertData()
{ {
Intent intent = new Intent(overviewView.getContext(), DataEntryActivity.class); Intent intent = new Intent(overviewView.getContext(), DataEntryActivity.class);
startActivityForResult(intent, 1); startActivityForResult(intent, 1);
} }
private class PieChartLastTouchListener implements PieChartOnValueSelectListener private class PieChartLastTouchListener implements PieChartOnValueSelectListener
{ {
@@ -467,7 +467,7 @@ public class OverviewFragment extends Fragment implements FragmentUpdateListener
public void onValueSelected(int lineIndex, int pointIndex, PointValue pointValue) { public void onValueSelected(int lineIndex, int pointIndex, PointValue pointValue) {
userSelectedData = scaleDataLastDays.get(pointIndex); userSelectedData = scaleDataLastDays.get(pointIndex);
updateOnView( OpenScale.getInstance(getContext()).getScaleDataList()); updateOnView(OpenScale.getInstance(getContext()).getScaleDataList());
} }
@Override @Override

View File

@@ -272,38 +272,38 @@ public class StatisticsFragment extends Fragment implements FragmentUpdateListen
info_month += String.format("Ø-"+getResources().getString(R.string.label_bmi)+": %.1f <br>", monthAvgBMI); info_month += String.format("Ø-"+getResources().getString(R.string.label_bmi)+": %.1f <br>", monthAvgBMI);
lines++; lines++;
if(prefs.getBoolean("fatEnable", true)) { if (prefs.getBoolean("fatEnable", true)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_fat)+": %.1f%% <br>", weekAvgFat); info_week += String.format("Ø-"+getResources().getString(R.string.label_fat)+": %.1f%% <br>", weekAvgFat);
info_month += String.format("Ø-"+getResources().getString(R.string.label_fat)+": %.1f%% <br>", monthAvgFat); info_month += String.format("Ø-"+getResources().getString(R.string.label_fat)+": %.1f%% <br>", monthAvgFat);
lines++; lines++;
} }
if(prefs.getBoolean("muscleEnable", true)) { if (prefs.getBoolean("muscleEnable", true)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_muscle)+": %.1f%% <br>", weekAvgMuscle); info_week += String.format("Ø-"+getResources().getString(R.string.label_muscle)+": %.1f%% <br>", weekAvgMuscle);
info_month += String.format("Ø-"+getResources().getString(R.string.label_muscle)+": %.1f%% <br>", monthAvgMuscle); info_month += String.format("Ø-"+getResources().getString(R.string.label_muscle)+": %.1f%% <br>", monthAvgMuscle);
lines++; lines++;
} }
if(prefs.getBoolean("lbwEnable", false)) { if (prefs.getBoolean("lbwEnable", false)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_lbw)+": %.1fkg <br>", weekAvgLBW); info_week += String.format("Ø-"+getResources().getString(R.string.label_lbw)+": %.1fkg <br>", weekAvgLBW);
info_month += String.format("Ø-"+getResources().getString(R.string.label_lbw)+": %.1fkg <br>", monthAvgLBW); info_month += String.format("Ø-"+getResources().getString(R.string.label_lbw)+": %.1fkg <br>", monthAvgLBW);
lines++; lines++;
} }
if(prefs.getBoolean("waterEnable", true)) { if (prefs.getBoolean("waterEnable", true)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_water)+": %.1f%% <br>", weekAvgWater); info_week += String.format("Ø-"+getResources().getString(R.string.label_water)+": %.1f%% <br>", weekAvgWater);
info_month += String.format("Ø-"+getResources().getString(R.string.label_water)+": %.1f%% <br>", monthAvgWater); info_month += String.format("Ø-"+getResources().getString(R.string.label_water)+": %.1f%% <br>", monthAvgWater);
lines++; lines++;
} }
if(prefs.getBoolean("boneEnable", false)) { if (prefs.getBoolean("boneEnable", false)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_bone)+": %.1fkg <br>", weekAvgBone); info_week += String.format("Ø-"+getResources().getString(R.string.label_bone)+": %.1fkg <br>", weekAvgBone);
info_month += String.format("Ø-"+getResources().getString(R.string.label_bone)+": %.1fkg <br>",monthAvgBone); info_month += String.format("Ø-"+getResources().getString(R.string.label_bone)+": %.1fkg <br>",monthAvgBone);
lines++; lines++;
} }
if(prefs.getBoolean("waistEnable", false)) { if (prefs.getBoolean("waistEnable", false)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_waist)+": %.1fcm <br>", weekAvgWaist); info_week += String.format("Ø-"+getResources().getString(R.string.label_waist)+": %.1fcm <br>", weekAvgWaist);
info_month += String.format("Ø-"+getResources().getString(R.string.label_waist)+": %.1fcm <br>", monthAvgWaist); info_month += String.format("Ø-"+getResources().getString(R.string.label_waist)+": %.1fcm <br>", monthAvgWaist);
lines++; lines++;
@@ -313,13 +313,13 @@ public class StatisticsFragment extends Fragment implements FragmentUpdateListen
lines++; lines++;
} }
if(prefs.getBoolean("hipEnable", false)) { if (prefs.getBoolean("hipEnable", false)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_hip)+": %.1fcm <br>", weekAvgHip); info_week += String.format("Ø-"+getResources().getString(R.string.label_hip)+": %.1fcm <br>", weekAvgHip);
info_month += String.format("Ø-"+getResources().getString(R.string.label_hip)+": %.1fcm <br>",monthAvgHip); info_month += String.format("Ø-"+getResources().getString(R.string.label_hip)+": %.1fcm <br>",monthAvgHip);
lines++; lines++;
} }
if(prefs.getBoolean("hipEnable", false) && prefs.getBoolean("waistEnable", false)) { if (prefs.getBoolean("hipEnable", false) && prefs.getBoolean("waistEnable", false)) {
info_week += String.format("Ø-"+getResources().getString(R.string.label_whr)+": %.2f <br>", weekAvgWHR); info_week += String.format("Ø-"+getResources().getString(R.string.label_whr)+": %.2f <br>", weekAvgWHR);
info_month += String.format("Ø-"+getResources().getString(R.string.label_whr)+": %.2f <br>", monthAvgWHR); info_month += String.format("Ø-"+getResources().getString(R.string.label_whr)+": %.2f <br>", monthAvgWHR);
lines++; lines++;

View File

@@ -74,8 +74,8 @@ import lecho.lib.hellocharts.util.ChartUtils;
import static android.util.TypedValue.COMPLEX_UNIT_DIP; import static android.util.TypedValue.COMPLEX_UNIT_DIP;
public class TableFragment extends Fragment implements FragmentUpdateListener { public class TableFragment extends Fragment implements FragmentUpdateListener {
private View tableView; private View tableView;
private ListView tableDataView; private ListView tableDataView;
private LinearLayout tableHeaderView; private LinearLayout tableHeaderView;
private SharedPreferences prefs; private SharedPreferences prefs;
private LinearLayout subpageView; private LinearLayout subpageView;
@@ -84,22 +84,22 @@ public class TableFragment extends Fragment implements FragmentUpdateListener {
private int selectedSubpageNr; private int selectedSubpageNr;
public TableFragment() { public TableFragment() {
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{ {
tableView = inflater.inflate(R.layout.fragment_table, container, false); tableView = inflater.inflate(R.layout.fragment_table, container, false);
subpageView = (LinearLayout) tableView.findViewById(R.id.subpageView); subpageView = (LinearLayout) tableView.findViewById(R.id.subpageView);
tableDataView = (ListView) tableView.findViewById(R.id.tableDataView); tableDataView = (ListView) tableView.findViewById(R.id.tableDataView);
tableHeaderView = (LinearLayout) tableView.findViewById(R.id.tableHeaderView); tableHeaderView = (LinearLayout) tableView.findViewById(R.id.tableHeaderView);
tableView.findViewById(R.id.btnImportData).setOnClickListener(new onClickListenerImport()); tableView.findViewById(R.id.btnImportData).setOnClickListener(new onClickListenerImport());
tableView.findViewById(R.id.btnExportData).setOnClickListener(new onClickListenerExport()); tableView.findViewById(R.id.btnExportData).setOnClickListener(new onClickListenerExport());
measurementsList = new ArrayList<>(); measurementsList = new ArrayList<>();
@@ -129,11 +129,11 @@ public class TableFragment extends Fragment implements FragmentUpdateListener {
selectedSubpageNr = 0; selectedSubpageNr = 0;
return tableView; return tableView;
} }
@Override @Override
public void updateOnView(ArrayList<ScaleData> scaleDataList) public void updateOnView(ArrayList<ScaleData> scaleDataList)
{ {
tableDataView.setAdapter(new ListViewAdapter(new ArrayList<HashMap<Integer, String>>())); // delete all data in the table with an empty adapter array list tableDataView.setAdapter(new ListViewAdapter(new ArrayList<HashMap<Integer, String>>())); // delete all data in the table with an empty adapter array list
@@ -245,7 +245,7 @@ public class TableFragment extends Fragment implements FragmentUpdateListener {
tableDataView.setAdapter(new ListViewAdapter(dataRowList)); tableDataView.setAdapter(new ListViewAdapter(dataRowList));
tableDataView.setOnItemClickListener(new onClickListenerRow()); tableDataView.setOnItemClickListener(new onClickListenerRow());
} }
private int pxImageDp(float dp) { private int pxImageDp(float dp) {
return (int)(dp * getResources().getDisplayMetrics().density + 0.5f); return (int)(dp * getResources().getDisplayMetrics().density + 0.5f);
@@ -396,7 +396,7 @@ public class TableFragment extends Fragment implements FragmentUpdateListener {
private ArrayList<HashMap<Integer, String>> dataList; private ArrayList<HashMap<Integer, String>> dataList;
private LinearLayout row; private LinearLayout row;
public ListViewAdapter(ArrayList<HashMap<Integer, String>> list){ public ListViewAdapter(ArrayList<HashMap<Integer, String>> list) {
super(); super();
this.dataList =list; this.dataList =list;
} }
@@ -422,7 +422,7 @@ public class TableFragment extends Fragment implements FragmentUpdateListener {
return convertView; return convertView;
} }
if(convertView == null){ if (convertView == null) {
row = new LinearLayout(getContext()); row = new LinearLayout(getContext());
convertView = row; convertView = row;

View File

@@ -135,12 +135,12 @@ public class BackupPreferences extends PreferenceFragment {
} }
private boolean importBackup(String databaseName, File exportDir) { private boolean importBackup(String databaseName, File exportDir) {
if(!isExternalStoragePresent()) if (!isExternalStoragePresent())
return false; return false;
File exportFile = new File(Environment.getDataDirectory() + File exportFile = new File(Environment.getDataDirectory() +
"/data/com.health.openscale" + "/data/com.health.openscale" +
"/databases/" + databaseName ); "/databases/" + databaseName);
File importFile = new File(exportDir, databaseName); File importFile = new File(exportDir, databaseName);
if (!importFile.exists()) { if (!importFile.exists()) {
@@ -161,12 +161,12 @@ public class BackupPreferences extends PreferenceFragment {
} }
private boolean exportBackup(String databaseName, File exportDir) { private boolean exportBackup(String databaseName, File exportDir) {
if(!isExternalStoragePresent()) if (!isExternalStoragePresent())
return false; return false;
File dbFile = new File(Environment.getDataDirectory() + File dbFile = new File(Environment.getDataDirectory() +
"/data/com.health.openscale" + "/data/com.health.openscale" +
"/databases/" + databaseName ); "/databases/" + databaseName);
File file = new File(exportDir, databaseName); File file = new File(exportDir, databaseName);

View File

@@ -82,14 +82,14 @@ public class UsersPreferences extends PreferenceFragment {
public void onActivityResult(int requestCode, int resultCode, Intent data) public void onActivityResult(int requestCode, int resultCode, Intent data)
{ {
if (requestCode == UserSettingsActivity.ADD_USER_REQUEST) { if (requestCode == UserSettingsActivity.ADD_USER_REQUEST) {
if(resultCode == RESULT_OK){ if (resultCode == RESULT_OK) {
updateUserPreferences(); updateUserPreferences();
} }
} }
if (requestCode == UserSettingsActivity.EDIT_USER_REQUEST) { if (requestCode == UserSettingsActivity.EDIT_USER_REQUEST) {
if(resultCode == RESULT_OK){ if (resultCode == RESULT_OK) {
updateUserPreferences(); updateUserPreferences();
} }
} }

View File

@@ -285,7 +285,7 @@ public abstract class MeasurementView extends TableLayout {
dateTime = objTimeDate; dateTime = objTimeDate;
value = String.valueOf(objValue); value = String.valueOf(objValue);
try{ try {
Float floatValue = Float.parseFloat(value); Float floatValue = Float.parseFloat(value);
if (measurementMode == VIEW || measurementMode == EDIT) { if (measurementMode == VIEW || measurementMode == EDIT) {
evaluate(floatValue); evaluate(floatValue);
@@ -306,7 +306,7 @@ public abstract class MeasurementView extends TableLayout {
if (diff > 0.0) { if (diff > 0.0) {
symbol = SYMBOL_UP; symbol = SYMBOL_UP;
symbol_color = "<font color='green'>" + SYMBOL_UP + "</font>"; symbol_color = "<font color='green'>" + SYMBOL_UP + "</font>";
} else if (diff < 0.0){ } else if (diff < 0.0) {
symbol = SYMBOL_DOWN; symbol = SYMBOL_DOWN;
symbol_color = "<font color='red'>" + SYMBOL_DOWN + "</font>"; symbol_color = "<font color='red'>" + SYMBOL_DOWN + "</font>";
} else { } else {
@@ -335,8 +335,8 @@ public abstract class MeasurementView extends TableLayout {
} }
} }
protected void setVisible(boolean isVisible){ protected void setVisible(boolean isVisible) {
if(isVisible) { if (isVisible) {
measurementRow.setVisibility(View.VISIBLE); measurementRow.setVisibility(View.VISIBLE);
} else { } else {
measurementRow.setVisibility(View.GONE); measurementRow.setVisibility(View.GONE);
@@ -378,7 +378,7 @@ public abstract class MeasurementView extends TableLayout {
evaluatorView.setLimits(evalResult.lowLimit, evalResult.highLimit); evaluatorView.setLimits(evalResult.lowLimit, evalResult.highLimit);
evaluatorView.setValue(value); evaluatorView.setValue(value);
switch(evalResult.eval_state) switch (evalResult.eval_state)
{ {
case LOW: case LOW:
indicatorView.setBackgroundColor(ChartUtils.COLOR_BLUE); indicatorView.setBackgroundColor(ChartUtils.COLOR_BLUE);