I saved the current date in SQLite and then retrieve the date from SQLite but every time the result is zero where is the problem??
My code to get the current date is
private String getDate() {
Calendar calendar = Calendar.getInstance();
@SuppressLint("SimpleDateFormat") SimpleDateFormat mdformat = new SimpleDateFormat("dd / MM / yyy ");
return mdformat.format(calendar.getTime());
}
and my code to save into SQLite
PrayDBHelper mDBHelper = new PrayDBHelper(PrayActivity.this);
SQLiteDatabase db = mDBHelper.getWritableDatabase();
db.execSQL("INSERT INTO " + prayEntry.TABLE_NAME + " " +prayEntry.DATE + " VALUES " +
getDate());
my code to retrive date from SQLite DB
dbConnection();
Cursor cursor= db.query(prayEntry.TABLE_NAME,prayEntry.DATE,null,null, null,
null,null);
while (cursor.moveToNext()) {
String date = (cursor.getString(0));// get Date
labelDATE.setText(date);
}
Never store dates in SQLite with a format different than YYYY-MM-DD
.
Anything else than this format will cause you trouble when it comes to query, compare and sort by this date.
For your code, this statement (including parentheses around the column name which must exist in your code or an exception would be thrown, so I guess this is just a typo):
"INSERT INTO "+prayEntry.TABLE_NAME+" ("+prayEntry.DATE +") VALUES "+getDate()
will save 0
in the table because getDate()
returns a value like: 19 / 12 / 2019
which is interpreted as integer divisions between the numbers 19, 12 and 2019 which result to 0
.
The reason is that you do not enclose the date inside single quotes, like:
"INSERT INTO "+prayEntry.TABLE_NAME+" ("+prayEntry.DATE +") VALUES '"+getDate()+"'"
But this is not the recommended way of doing insertions.
Use the method insert()
and ContentValues()
like this:
PrayDBHelper mDBHelper = new PrayDBHelper(PrayActivity.this);
SQLiteDatabase db = mDBHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(prayEntry.DATE, getDate());
db.insert(prayEntry.TABLE_NAME, cv);
db.close();