android - 如何获取当前日期并将其存储到 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
. 那么有什么方法可以将日期存储为int
or long
?
解决方案
您可以将当前时间戳添加到您的数据库条目并从中读取日期
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" +");"
}
推荐阅读
- python - 如何创建具有重复键的字典并形成字典列表
- javascript - 在提交 html 表单上显示成功消息
- heroku - 带有 GoDaddy 域的 Heroku 无法正常工作
- java - Java Parse Json Array in another Json Array json.simple
- javascript - 如何使用 Angular 中连接的所有字段访问嵌套 JSON 中的值?
- python-3.x - 从 __init__.py 中访问 import 语句(或在导入子模块时如何不运行 __init__.py)
- javascript - vuetify 数据表计算属性到 sql
- symfony - Symfony 无法显示浮点数
- java - 从 ObservableList 中提取元素
- python - 尝试使用 CV2 和 numpy 调整图像的大小和形状