如何从按钮单击中获取数据并将其添加到数据库中

时间:2018-05-08 21:39:06

标签: android database sqlite

我想在用户注册数据库中保存每个计算结果和日期,然后根据这些数据制作图表。获取结果的代码是:

public double doCalories(boolean fem, boolean male, double age, double weight, double feet, double inches){

    DisplayDateTime = (TextView)findViewById(R.id.date_test);
    calander = Calendar.getInstance();
    simpledateformat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    Date = simpledateformat.format(calander.getTime());
    DisplayDateTime.setText(Date);


    double bmrResult = 0;
    double height_in_inches;

    if (MainActivity.unit_is_gram){
        weight = weight * 2.2;
    }

    if (MainActivity.unit_is_meter){
        height_in_inches = 0.39370* inches; //actually is 0.39370 * centimeters
    }

    else height_in_inches = (feet*12)+inches;

    if (fem == true) {

        bmrResult = 10*(weight/2.2)+6.25*(height_in_inches*2.54)-5*age-161;
    }

    else if (male == true){


        bmrResult = 10*(weight/2.2)+6.25*(height_in_inches*2.54)-5*age+5;
    }



    return bmrResult;
}

DataBase Activity中的用户数据库代码为:

private static final String DATABASE_NAME = "UserManager.db";

// User table name
private static final String TABLE_USER = "user";

// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";


// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
        + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
        + COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

如何将数据库与结果相结合?我知道我必须在数据库中添加字段,但我不知道哪种字段以及如何从卡路里活动中获取数据。

1 个答案:

答案 0 :(得分:0)

你可能想要一个额外的表,比如命名读数,它将引用相应的用户,读数的日期/时间和结果以及可能使用的值。

所以也许有: -

// Reading Table name
private static final String TABLE_READING = "reading";

//Reading Table Column Names
private static final String COLUMN_READING_USERREFERENCE = "reading_user_reference";
private static final String COLUMN_READING_DATETIME = "reading_datetime";
private static final String COLUMN_READING_AGE = "reading_age"; //<<< shouldn't really be needed as Age could be calculated if date of birth were stored in g user_table
private static final String COLUMN_READING_WEIGHT = "reading_weight";
private static final String COLUMN_READING_HEIGHT_FEET = "reading_height_feet";
private static final String COLUMN_READING_HEIGHT_INCHES = "reading_height_inches";
private static final String COLUMN_READING_RESULT = "reading_calories"; //<<< could do without

//Create Reading Table SQL
private static final String CREATE_READING_TABLE =
        "CREATE TABLE IF NOT EXISTS " + TABLE_READING +
                "(" +
                COLUMN_READING_USERREFERENCE + " INTEGER NOT NULL, " +
                COLUMN_READING_DATETIME + " TEXT DEFAULT CURRENT_TIMESTAMP, " +
                COLUMN_READING_AGE + " REAL," +
                COLUMN_READING_WEIGHT + " REAL," +
                COLUMN_READING_HEIGHT_FEET + " INTEGER," +
                COLUMN_READING_HEIGHT_INCHES + " INTEGER," +
                COLUMN_READING_RESULT + " REAL" +
                ")";

然后,您可能希望能够添加一个读数,或许有(注意两个签名允许默认日期时间(即现在)或特定数据时间): -

//Add using specific timestamp
public long addReading(
        long user,
        long timestamp,
        double age,
        double weight,
        double height_feet,
        double height_inches,
        double result) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = new Date(timestamp * 1000);
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_READING_USERREFERENCE,user);
    if (timestamp != 0) {
        cv.put(COLUMN_READING_DATETIME,sdf.format(date));
    }
    cv.put(COLUMN_READING_AGE,age);
    cv.put(COLUMN_READING_WEIGHT,weight);
    cv.put(COLUMN_READING_HEIGHT_FEET,(int) height_feet);
    cv.put(COLUMN_READING_HEIGHT_INCHES,(int) height_inches);
    cv.put(COLUMN_READING_RESULT,result);
    return db.insert(TABLE_READING,null,cv);
}

//Add user timestamp deault i.e. date/time now
public long addReading(long user,
                       double age,
                       double weight,
                       double height_feet,
                       double height_inches,
                       double result) {
    return addReading(user,0,
            age,
            weight,
            height_feet,
            height_inches,
            result
    );
}
  • 注意签名与doCalories方法类似。

这是一个示例方法,它将返回结果以及用户详细信息: -

public Cursor getAllResultsWithUserDetails() {
    String[] columns_to_include_in_cursor = new String[]{
            COLUMN_USER_ID,
            COLUMN_USER_NAME,
            COLUMN_USER_EMAIL,
            "datetime(" + COLUMN_READING_DATETIME + ") AS reading_taken",
            COLUMN_READING_WEIGHT,
            COLUMN_READING_HEIGHT_FEET + "||'feet '||" + COLUMN_READING_HEIGHT_INCHES+"||'inches' AS height",
            COLUMN_READING_RESULT
    };
    return this.getWritableDatabase().query(
            TABLE_READING +
                    " JOIN " +
                    TABLE_USER +
                    " ON " +
                    TABLE_USER + "." +  COLUMN_USER_ID +
                    " = " +
                    TABLE_READING + "." + COLUMN_READING_USERREFERENCE,
            columns_to_include_in_cursor,
            null,
            null,
            null,
            null,
            COLUMN_READING_DATETIME + " DESC"
    );
}

注释

  • 结果(等效)SQL将是: -
    • SELECT user_id, user_name, user_email, datetime(reading_datetime) AS reading_taken, reading_weight, reading_height_feet||'feet' ||reading_height_inches||'inches' AS height, reading_calories FROM reading JOIN user ON user.user_id = reading.reading_user_reference ORDER BY reading_datetime DESC

这是另一种在日志中显示结果的方法(即它使用getAllResultsWithUserDetails方法): -

public void logAllResults() {
    Cursor csr = getAllResultsWithUserDetails();
    while (csr.moveToNext()) {
        Log.d("RESULTS",
                "Name = " + csr.getString(csr.getColumnIndex(COLUMN_USER_NAME)) +
                        " (id=" +
                        String.valueOf(csr.getLong(csr.getColumnIndex(COLUMN_USER_ID))) + ") " +
                        "\n\tDate/Time of Reading = " +
                        csr.getString(csr.getColumnIndex("reading_taken")) +
                        "\n\tWeight = " +
                        csr.getString(csr.getColumnIndex(COLUMN_READING_WEIGHT)) +
                        "\n\tHeight = " +
                        csr.getString(csr.getColumnIndex("height")) +
                        "\n\tCalories = " +
                        csr.getString(csr.getColumnIndex(COLUMN_READING_RESULT))
                );
    }
    csr.close();
}

将它们放在一起进行演示(上面的代码位于DBHelper(即SQLiteOpenHelper的子类)中,名为DBHelper),以下是一个活动: -

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DBHelper dbhlpr = new DBHelper(this);
    dbhlpr.addUser(
            "Fred",
            "fred@fredmail.com","" +
                    "fredspassword"
    );
    dbhlpr.addReading(1,23,65.7,6,2,4567.78);
    // Add with specific date time (2018-04-30 12:45:00)
    dbhlpr.addReading(1,1525092300, 23,68.2,6,1,5678.67);
    dbhlpr.logAllResults();
}
  1. 首先是正常的活动,即调用super方法并设置活动的布局。
  2. 实例化DBHelper类。
  3. 使用fred@fredmail.com等电子邮件添加名为Fred的用户
  4. 使用默认日期/时间添加阅读。
  5. 使用给定的日期/时间添加阅读。
  6. 显示阅读结果
  7. 结果

    logAllresults 的结果是: -

    05-09 01:41:37.878 2092-2092/fred.caloriecalc D/RESULTS: Name = Fred (id=1) 
          Date/Time of Reading = 2018-05-09 01:41:37
          Weight = 65.7
          Height = 6feet 2inches
          Calories = 4567.78
        Name = Fred (id=1) 
          Date/Time of Reading = 2018-04-30 12:45:00
          Weight = 68.2
          Height = 6feet 1inches
          Calories = 5678.67