I want to get the current date and store it inside SQLite. After that, I want to use it in my graph.
Here is my code for storing data:
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();
}
};
And here is my SQLite Helper:
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));
}
}
And here is my code for adding data to 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));
}
}
I know I can't do this dp [i] = new DataPoint(helper.getDate(cursor), helper.getWeight(cursor)); because the date is stored as String. So is there any way which I can store the date as int or long?
You can add the current timestamp to your database entry and read the date out of this
The format of a TIMESTAMP is YYYY-MM-DD HH:MM:SS at the second when you create the entry.
So you dont have to create it by your own. If I only need the date I read the line out an split the text. The advantage is that when sorting the entries by time, the seconds are also taken into account.
Update: Your table should look somethink like this