首页 > 解决方案 > 如何获取当前日期并将其存储到 sqlite。之后将其绘制在 x 轴的图中?

问题描述

我想获取当前日期并将其存储在 SQLite 中。之后,我想在我的图表中使用它。

这是我存储数据的代码:

private View.OnClickListener onCalculate = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        double weight = Double.parseDouble(Weight.getText().toString());
        
        String date = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(new Date());

        helper.insert(weight, date);

        finish();
    }
};

这是我的 SQLite 助手:

public class Helper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "bmi.db";
private static final int SCHEMA_VERSION = 1;

public BMIHelper(Context context) {
    super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE bmi_table ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "weight REAL, date TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

public Cursor getAll() {
    return (getReadableDatabase().rawQuery("SELECT _id, weight, date " +
            "FROM bmi_table ORDER BY _id", null));
}

public void insert(Double weight, String date) {
    ContentValues cv = new ContentValues();

    cv.put("weight", weight);
    cv.put("date", date);

    getWritableDatabase().insert("bmi_table", "weight", cv);
}

public double getWeight(Cursor c) {
    return (c.getDouble(1));
}

public String getDate(Cursor c) {
    return (c.getString(2));
}
}

这是我将数据添加到 GraphView 的代码:

private DataPoint[] getDataPoint() {
    String[] columns = {"Date", "Weight"};
    DataPoint[] dp = new DataPoint[cursor.getCount()];

    for (int i = 0; i < cursor.getCount(); i++) {
        cursor.moveToNext();
        dp [i] = new DataPoint(helper.getDate(cursor), helper.getWeight(cursor));
    }
}

我知道我不能这样做,dp [i] = new DataPoint(helper.getDate(cursor), helper.getWeight(cursor));因为日期存储为String. 那么有什么方法可以将日期存储为intor long

标签: androidandroid-graphviewandroid-date

解决方案


您可以将当前时间戳添加到您的数据库条目并从中读取日期

date + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP"

创建条目时,TIMESTAMP 的格式为 YYYY-MM-DD HH:MM:SS。

所以你不必自己创建它。如果我只需要日期,我会读出该行并拆分文本。优点是在按时间对条目进行排序时,也会考虑秒数。

更新:你的桌子应该看起来像这样

@Override
public void onCreate(SQLiteDatabase db) {
   db.execSQL("CREATE TABLE bmi_table ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
   "weight REAL, " +
    date + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +");"
}

推荐阅读