Hey I am trying to query my database for the number of records which match the current date and also match the current time in the same record, however, I am getting a "Cannot resolve method "query(java.lang.string)"
What I need the query to do is check if a records date, and time match the current date and time.
Here is my DatabaseHandler class file
public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "FoodTekTrakr",
DATABASE_TABLE = "AlarmManager",
KEY_ID = "id",
KEY_TITLE = "title",
KEY_DATE = "date",
KEY_TIME = "time",
KEY_SONG = "song";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TITLE + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT," + KEY_SONG + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public void createAlarm(UserInputAlarmData AlarmData){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, AlarmData.getTitle());
values.put(KEY_DATE, AlarmData.getDate());
values.put(KEY_TIME, AlarmData.getTime());
values.put(KEY_SONG, AlarmData.getSong());
db.insert(DATABASE_TABLE, null, values);
db.close();
}
public UserInputAlarmData getAlarmData(int id){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_TITLE, KEY_DATE, KEY_TIME, KEY_SONG}, KEY_ID
+ "=?", new String[] {String.valueOf(id) }, null, null, null );
if (cursor != null)
cursor.moveToFirst();
UserInputAlarmData AlarmData = new UserInputAlarmData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
db.close();
cursor.close();
return AlarmData;
}
public void deleteAlarm(UserInputAlarmData AlarmData){
SQLiteDatabase db = getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + "=?", new String[] { String.valueOf(AlarmData.getId()) });
db.close();
}
public int getAlarmDataCount() {
SQLiteDatabase db =getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateAlarmData(UserInputAlarmData AlarmData){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, AlarmData.getTitle());
values.put(KEY_DATE, AlarmData.getDate());
values.put(KEY_TIME, AlarmData.getTime());
values.put(KEY_SONG, AlarmData.getSong());
return db.update(DATABASE_TABLE, values, KEY_ID + "=?", new String[] { String.valueOf(AlarmData.getId())});
}
public List<UserInputAlarmData> getAllAlarmData() {
List<UserInputAlarmData> AlarmDatas = new ArrayList<UserInputAlarmData>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
if (cursor.moveToFirst()) {
do {
UserInputAlarmData AlarmData = new UserInputAlarmData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
AlarmDatas.add(AlarmData);
}
while (cursor.moveToNext());
}
return AlarmDatas;
}
public boolean DateAndTimeChecker() {
Date ThisDate = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String DateChecker = formatter.format(ThisDate);
Date ThisTime = Calendar.getInstance().getTime();
SimpleDateFormat timeformatter = new SimpleDateFormat("hh:mm");
String TimeChecker = formatter.format(ThisTime);
String DatabaseTime;
SQLiteDatabase db =getReadableDatabase();
Cursor c = db.query("SELECT " + KEY_DATE + "WHERE"+ KEY_TIME + "=" + DateChecker + "FROM" + DATABASE_TABLE);
if(c != null) {
return true;
}
else{
return false;
}
}
}
The method in which I am getting the error
public boolean DateAndTimeChecker() {
Date ThisDate = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String DateChecker = formatter.format(ThisDate);
Date ThisTime = Calendar.getInstance().getTime();
SimpleDateFormat timeformatter = new SimpleDateFormat("hh:mm");
String TimeChecker = formatter.format(ThisTime);
String DatabaseTime;
SQLiteDatabase db =getReadableDatabase();
Cursor c = db.query("SELECT " + KEY_DATE + "WHERE"+ KEY_TIME + "=" + DateChecker + "FROM" + DATABASE_TABLE);
if(c != null) {
return true;
}
else{
return false;
}
}
Thank you very much in advance for the help
You need add second parameter on rawQuery
Cursor c = db.query(..., null);
Late to the party but I think the issue here is that your select statement is not correct. The correct format for a select statement is: SELECT column_name FROM table_name WHERE [condition].
Related
I'm trying to get all records in list view from sqlite database but getting exception of IllegalStateException: Cannot perform this operation because the connection pool has been closed. again and again . If I remove db.close(); even then getting same issue . How to resolve this issue.
Here is my code in db helper class.
public class MyDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ClassNKK.db";
public static final int DATABASE_VERSION = 4;
private Context context;
public SQLiteDatabase db;
String str_Authentication_Token;
String str_LoginUserId;
String str_UserName;
String str_UserRole;
public MyDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
this.context = context;
#Override
public void onCreate(SQLiteDatabase db) {.....}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS " + Table_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Table_COMPANY);
db.execSQL("DROP TABLE IF EXISTS " + Table_VesselList);
db.execSQL("DROP TABLE IF EXISTS " + Table_Inspector_List);
db.execSQL("DROP TABLE IF EXISTS " + Table_AllPost_Table);
db.execSQL("DROP TABLE IF EXISTS " + Table_ActivityObjectList);
db.execSQL("DROP TABLE IF EXISTS " + Table_FollowUpList);
db.execSQL("DROP TABLE IF EXISTS " + Table_SyncTime);
db.execSQL("DROP TABLE IF EXISTS " + Table_VEsselHashTag);
db.execSQL("DROP TABLE IF EXISTS " + Table_FollowUpSettings);
onCreate(db);
public boolean update_AllPost(String strActivityStatus, String strActivityId,
String strRemark,
String strName,
String strInspectorName,
String strShortname,
String strHashTag,
String strStatus,
String strType,
String strUserId,
String strObjectId,
String strActiondate,
String strStarFlag,
String strDownLoadStatus,
String strUpLoadStatus,
String strStarMarkUpLoadStatus,
String strUpLoad_FollowUpStatus,
String strUpLoad_UnFollowUpStatus )
{
SQLiteDatabase db1 = getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COL_AllPost_ActivityStatus, strActivityStatus);
args.put(COL_AllPost_PostActivityId, strActivityId);
args.put(COL_AllPost_Remark, strRemark);
args.put(COL_AllPost_Title, strName);
args.put(COL_AllPost_inspectorname, strInspectorName);
args.put(COL_AllPost_shortName, strShortname);
args.put(COL_AllPost_HashTag, strHashTag);
args.put(COL_AllPost_Status, strStatus);
args.put(COL_AllPost_Type, strType);
args.put(COL_AllPost_UserId, strUserId);
args.put(COL_AllPost_VesselId, strObjectId);
args.put(COL_AllPost_ActionDate, strActiondate);
args.put(COL_AllPost_StarFlag, strStarFlag);
args.put(COL_AllPost_DownLoadStatus, strDownLoadStatus);
args.put(COL_ALLPOST_UpLoad_Status , strUpLoadStatus);
args.put(COL_ALLPOST_UpLoad_StarMark_Status ,strStarMarkUpLoadStatus);
args.put(COL_ALLPOST_UpLoad_FollowUpStatus ,strUpLoad_FollowUpStatus);
args.put(COL_ALLPOST_UpLoad_UnFollowUpStatus ,strUpLoad_UnFollowUpStatus);
int i = db1.update(Table_AllPost_Table, args, COL_AllPost_PostActivityId + "=" + strActivityId, null);
return i > 0;
}
public boolean update_FollowUpPost(String Followup,
String FollowupType,
String activityId,
String createdBy,
String date,
String editableFlag,
String follow_id,
int followupId,
String objectId,
String followUp_UpLoadStatus
)
{
SQLiteDatabase db1 = getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COL_Followup, Followup);
args.put(COL_FollowupType , FollowupType);
args.put(COL_Followup_activityId, activityId);
args.put(COL_Followup_createdBy, createdBy);
args.put(COL_Followup_date, date);
args.put(COL_Followup_editableFlag, editableFlag);
args.put(COL_FID, follow_id);
args.put(COL_followupId, followupId);
args.put(COL_Followup_objectId, objectId);
args.put(COL_FollowUp_UpLoadStatus , followUp_UpLoadStatus);
int i = db1.update(Table_FollowUpList, args, COL_followupId + "=" + followupId, null);
return i > 0;
}
}
public boolean isAllPostId_Exist(String activityId) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Table_AllPost_Table, new String[]{COL_AllPost_PostActivityId}, COL_AllPost_PostActivityId + "=?",
new String[]{String.valueOf(activityId)}, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() == 0) {
cursor.close();
db.close();
return false;
} else {
cursor.close();
db.close();
return true;
}
}
return false;
}
public boolean isConpany_IdExit(String strCompanyId) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Table_COMPANY, new String[]{COL_Company_Id}, COL_Company_Id + "=?",
new String[]{String.valueOf(strCompanyId)}, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() == 0) {
// Log.e("Row is Not ", " Exist in Table_VesselList Table in MyDbHelper");
cursor.close();
db.close();
return false;
} else {
// Log.e("Row is already ", " Exist in Table_VesselList Table in MyDbHelper ");
cursor.close();
db.close();
return true;
}
}
return false;
}
public boolean isActivityObject_ImageAudioPath(String str_ImageAudioPath) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Table_ActivityObjectList, new String[]{COL_imageaudioPath}, COL_imageaudioPath + "=?",
new String[]{String.valueOf(str_ImageAudioPath)}, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() == 0) {
cursor.close();
db.close();
return false;
} else {
cursor.close();
db.close();
return true;
}
}
return false;
}
public boolean isExistNotation(String str_Notation) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Table_VEsselHashTag, new String[]{VesselHashTag}, VesselHashTag + "=?",
new String[]{String.valueOf(str_Notation)}, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() == 0) {
//Log.e("Row is Not ", " Exist in ActivityObjectList Table in MyDbHelper");
cursor.close();
db.close();
return false;
} else {
//Log.e("Row is already ", " Exist in ActivityObjectList Table in MyDbHelper ");
cursor.close();
db.close();
return true;
}
}
return false;
}
public void insertCompany(String strCompanyId, String strCompanyName) {
SQLiteDatabase db1 = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(COL_Company_Id, strCompanyId);
values.put(COL_CompanyName, strCompanyName);
db1.insert(Table_COMPANY, null, values);
db1.close();
}
/*********************************************************************************************************/
#Override
public synchronized void close() {
if (db != null) {
db.close();
super.close();
}
}
/********************************************************************************************************/
public boolean updateStarFlag(String str_ActivityId, String str_StarFlag, String str_StarMark_UpLoadStatus) {
SQLiteDatabase db1 = getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COL_AllPost_PostActivityId, str_ActivityId);
args.put(COL_AllPost_StarFlag, str_StarFlag);
args.put(COL_ALLPOST_UpLoad_StarMark_Status, str_StarMark_UpLoadStatus);
int i = db1.update(Table_AllPost_Table, args, COL_AllPost_PostActivityId + "= ? ", new String[]{str_ActivityId});
return i > 0;
}
public void insert_VesselList(String strACtiveStatus, String strVessCompanyId, String strVesselName, String strVesseleId, String strVesselsTypeId, String VesselsTypeName, String strClassCodeNumber, String strIsFollowedVessels) {
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(COL_ACtiveStatus, strACtiveStatus);
values.put(COL_VessCompanyId, strVessCompanyId);
values.put(COL_VesselName, strVesselName);
values.put(COL_VesseleId, strVesseleId);
values.put(COL_VesselsTypeId, strVesselsTypeId);
values.put(COL_VesselsTypeName, VesselsTypeName);
values.put(COL_ClassCodeNumber, strClassCodeNumber);
values.put(COL_IsFollowedVessels, strIsFollowedVessels);
db.insert(Table_VesselList, null, values);
db.close();
}
public boolean isUserDetails_Exist(String strUserName) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Table_NAME, new String[]{COL_Username}, COL_Username + "=?",
new String[]{String.valueOf(strUserName)}, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() == 0) {
// Log.e("Row is Not ", " Exist in Table_VesselList Table in MyDbHelper");
cursor.close();
db.close();
return false;
} else {
// Log.e("Row is already ", " Exist in Table_VesselList Table in MyDbHelper ");
cursor.close();
db.close();
return true;
}
}
return false;
}
public List<All_Post> getMyAll_StarPost(int OFFSET) {
List<All_Post> allPostDescList = new ArrayList<All_Post>();
String selectQuery = "select * from " + Table_AllPost_Table + " where StarFlag='1' AND ActiveStatus = '1' AND Status = 'PENDING' ORDER BY ActionDate DESC LIMIT 50 OFFSET "+OFFSET ; // LIMIT 50 OFFSET "+OFFSET;
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
All_Post allPostDesc = new All_Post();
allPostDesc.setID(cursor.getInt(cursor.getColumnIndex("ALL_ACT_ID")));
allPostDesc.setStrActiveStatus(cursor.getString(cursor.getColumnIndex("ActiveStatus")));
allPostDesc.setStrActivityId(cursor.getString(cursor.getColumnIndex("ActivityId")));
allPostDesc.setStrRemark(cursor.getString(cursor.getColumnIndex("Remark")));
allPostDesc.setStrProfilePic(cursor.getString(cursor.getColumnIndex("ProfilePICURL")));
allPostDesc.setStringInspectorname(cursor.getString(cursor.getColumnIndex("inspectorName")));
allPostDesc.setStrNotationNo(cursor.getString(cursor.getColumnIndex("HashTag")));
allPostDesc.setStrUserId(cursor.getString(cursor.getColumnIndex("UserId")));
allPostDesc.setStrvessel_Id(cursor.getString(cursor.getColumnIndex("VesselId")));
String strSqliteDate = cursor.getString(cursor.getColumnIndex("ActionDate"));
allPostDesc.setStrStarFlag(cursor.getString(cursor.getColumnIndex("StarFlag")));
allPostDesc.setStrDownLoadStatus(cursor.getString(cursor.getColumnIndex("DownLoad_Status")));
if (strSqliteDate != null && !strSqliteDate.isEmpty()) {
String result = "";
Date date1 = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
date1 = dateFormat.parse(strSqliteDate);
} catch (Exception e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
SimpleDateFormat printFormat = new SimpleDateFormat("yyyy-MM-dd");
result = printFormat.format(calendar.getTime());
//Log.e("result = ","==========>"+result);
allPostDesc.setActiondate(result);
}
allPostDescList.add(allPostDesc);
} while (cursor.moveToNext());
db.close();
}
return allPostDescList;
}
public List<All_Post> getMyAllPost(String strUserId , int OFFSET) {
List<All_Post> allPostDescList = new ArrayList<All_Post>();
String selectQuery = "select * from " + Table_AllPost_Table + " where UserId=" + strUserId + " AND ActiveStatus = '1' AND Status = 'PENDING' ORDER BY ActionDate DESC LIMIT 50 OFFSET "+OFFSET;
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
All_Post allPostDesc = new All_Post();
allPostDesc.setID(cursor.getInt(cursor.getColumnIndex("ALL_ACT_ID")));
allPostDesc.setStrActiveStatus(cursor.getString(cursor.getColumnIndex("ActiveStatus")));
allPostDesc.setStrActivityId(cursor.getString(cursor.getColumnIndex("ActivityId")));
allPostDesc.setStrRemark(cursor.getString(cursor.getColumnIndex("Remark")));
allPostDesc.setStrProfilePic(cursor.getString(cursor.getColumnIndex("ProfilePICURL")));
allPostDesc.setStringInspectorname(cursor.getString(cursor.getColumnIndex("inspectorName")));
allPostDesc.setStrNotationNo(cursor.getString(cursor.getColumnIndex("HashTag")));
allPostDesc.setStrUserId(cursor.getString(cursor.getColumnIndex("UserId")));
allPostDesc.setStrvessel_Id(cursor.getString(cursor.getColumnIndex("VesselId")));
String strSqliteDate = cursor.getString(cursor.getColumnIndex("ActionDate"));
allPostDesc.setStrStarFlag(cursor.getString(cursor.getColumnIndex("StarFlag")));
allPostDesc.setStrDownLoadStatus(cursor.getString(cursor.getColumnIndex("DownLoad_Status")));
if (strSqliteDate != null && !strSqliteDate.isEmpty()) {
String result = "";
Date date1 = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
date1 = dateFormat.parse(strSqliteDate);
} catch (Exception e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
SimpleDateFormat printFormat = new SimpleDateFormat("yyyy-MM-dd");
result = printFormat.format(calendar.getTime());
//Log.e("result = ","==========>"+result);
allPostDesc.setActiondate(result);
}
allPostDescList.add(allPostDesc);
} while (cursor.moveToNext());
db.close();
}
return allPostDescList;
}
public List<All_Post> getAllDescriptions(int OFFSET)
{
List<All_Post> allPostDescList = new ArrayList<All_Post>();
String selectQuery = "select * from " + Table_AllPost_Table + " where ActiveStatus = '1' AND Status = 'PENDING' ORDER BY ActionDate DESC LIMIT 50 OFFSET "+OFFSET; //ORDER BY ActionDate DESC
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
All_Post allPostDesc = new All_Post();
allPostDesc.setID(cursor.getInt(cursor.getColumnIndex("ALL_ACT_ID")));
allPostDesc.setStrActiveStatus(cursor.getString(cursor.getColumnIndex("ActiveStatus")));
allPostDesc.setStrActivityId(cursor.getString(cursor.getColumnIndex("ActivityId")));
allPostDesc.setStrRemark(cursor.getString(cursor.getColumnIndex("Remark")));
allPostDesc.setStrProfilePic(cursor.getString(cursor.getColumnIndex("ProfilePICURL")));
allPostDesc.setStringInspectorname(cursor.getString(cursor.getColumnIndex("inspectorName")));
allPostDesc.setStrNotationNo(cursor.getString(cursor.getColumnIndex("HashTag")));
allPostDesc.setStrShortName(cursor.getString(cursor.getColumnIndex("Type")));
allPostDesc.setStrUserId(cursor.getString(cursor.getColumnIndex("UserId")));
allPostDesc.setStrvessel_Id(cursor.getString(cursor.getColumnIndex("VesselId")));
String strSqliteDate = cursor.getString(cursor.getColumnIndex("ActionDate"));
if (strSqliteDate != null && !strSqliteDate.isEmpty()) {
String result = "";
Date date1 = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
date1 = dateFormat.parse(strSqliteDate);
} catch (Exception e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
SimpleDateFormat printFormat = new SimpleDateFormat("dd-MM-yyyy");
result = printFormat.format(calendar.getTime());
//Log.e("result = ","==========>"+result);
allPostDesc.setActiondate(result);
}
allPostDesc.setStrStarFlag(cursor.getString(cursor.getColumnIndex("StarFlag")));
allPostDesc.setStrDownLoadStatus(cursor.getString(cursor.getColumnIndex("DownLoad_Status")));
allPostDescList.add(allPostDesc);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return allPostDescList;
}
}
I have events table contains start time, end time,dayOfWeek ,location etc. I want to retrieve records based on dayOfweek. I am saving dayOfWeek as string.("Mon","Tue",etc..).
How can I retrieve record for each day?
This is my EventTableHelper.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
private static final String KEY_LOCATION = "location";
private static final String KEY_NOTIFICATION_TIME = "notification";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT,"
+ KEY_LOCATION + " TEXT,"
+ KEY_NOTIFICATION_TIME + "TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE, KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5),cursor.getString(6));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setDayOfWeek(cursor.getString(4));
event.setLocation(cursor.getString(5));
event.setNotificationTime(cursor.getString(6));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
public int updateEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE,event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
// updating row
return db.update(TABLE, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.getId()) });
}
public void deleteEvent(EventData eventData) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE, KEY_ID + " = ?",
new String[]{String.valueOf(eventData.getId())});
db.close();
}
}
I tried to retrieve like this:
public List<EventData> getAllEvents(String day) {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE + " WHERE (" + KEY_DAY_OF_WEEK + " = " + day;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setDayOfWeek(cursor.getString(4));
event.setLocation(cursor.getString(5));
event.setNotificationTime(cursor.getString(6));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
But it's giving Syntax error :
android.database.sqlite.SQLiteException: near "Mon": syntax error (code 1): , while compiling: SELECT * FROM event WHERE (dayofweek = Mon)
I am retrieving events like this:
String day = "Mon"
mDb = new EventTableHelper(getActivity());
events = mDb.getAllEvents(day);
I am saving dayOfWeek in another activity. I want to retrieve records in fragment. I don't have idea how to pass day parameter in function.
Do like Pass value in single quote
String selectQuery = "SELECT * FROM " + TABLE + " WHERE " + KEY_DAY_OF_WEEK +" = '"+day+ "'";
Replace this
String selectQuery = "SELECT * FROM " + TABLE + " WHERE (" + KEY_DAY_OF_WEEK + " = " + day;
To
String selectQuery = "SELECT * FROM " + TABLE + " WHERE " + KEY_DAY_OF_WEEK + " = '" + day + "'";
I am having difficulty inserting image in my sqlite database. There are no syntax errors in my code. After I run it, the app automatically force stops. The logcat shows:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at com.synergy88studios.catalogapp.DatabaseHandler.getAllItemsInList(DatabaseHandler.java:86)
at com.synergy88studios.catalogapp.MainActivity.onCreate(MainActivity.java:56)
Here is my method in getAllItemsInList in my DatabaseHandler.class
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
In my MainActivity, I simply call the method.
items = db.getAllItemsInList();
EDIT
DatabaseHandler.class
public class DatabaseHandler extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "CatalogItems";
public static final String TABLE_ITEMS = "Items";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DESC = "description";
public static final String KEY_IMAGE = "image";
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_DESC};
//private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "( "
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT, " + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_ITEMS);
onCreate(db);
}
public void addItems(Item item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
db.insert(TABLE_ITEMS, null ,values);
db.close();
}
Item getItem(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC , KEY_IMAGE}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getBlob(3));
return item;
}
void deleteAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+ TABLE_ITEMS);
}
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
String where = null;
Cursor c = db.query(true, TABLE_ITEMS, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public int getItemsCount(){
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
}
public void deleteContact(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
db.close();
}
}
I hope someone can explain to me what happens. I can post my other classes for reference.
Don't store large data in an Android sqlite table. In particular, the CursorWindow only supports row data up to 2MB. If your row is larger, you can't access it.
Instead, store your blobs as files in the filesystem and store just the path in database.
I wrote a simple database helper class to make access to the DB from multiple activities more clean.
Here's the class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "name";
private static final String TABLE_SCORES = "scores";
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "score";
private static final String KEY_DATE = "date";
SQLiteDatabase database;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
String CREATE_SCORES_TABLE = "CREATE TABLE " + TABLE_SCORES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_SCORE + " INTEGER,"
+ KEY_DATE + " TEXT" + ")";
database.execSQL(CREATE_SCORES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
onCreate(database);
}
void addScore(int score){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
String currentDateandTime = dateFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
values.put(KEY_DATE, currentDateandTime);
database.insert(TABLE_SCORES, null, values);
//database.close();
}
void delete(){
database.delete(TABLE_SCORES, null, null);
}
public List<Score> getAllScores(){
List<Score> scoresList = new ArrayList<Score>();
String selectQuery = "SELECT * FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 10";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Score score = new Score();
score.setId(Integer.parseInt(cursor.getString(0)));
score.setScore(Integer.parseInt(cursor.getString(1)));
score.setDate(cursor.getString(2));
scoresList.add(score);
} while (cursor.moveToNext());
}
return scoresList;
}
public int getHighscore() {
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_SCORE +" DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return 0;
}
public int getLastScoreID(){
String selectQuery = "SELECT " + KEY_ID + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
public int getLastScoreValue(){
String selectQuery = "SELECT " + KEY_SCORE + " FROM " + TABLE_SCORES + " ORDER BY " + KEY_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
return cursor.getInt(0);
}
else return -1;
}
}
Here's the question:
where should I put database.close()? There's no such thing like destructor in Java (I really don't want to finalize() this one...).
Best regards.
Override the close() method of the SQLiteOpenHelper class
#Override
public synchronized void close() {
database.close();
super.close();
}
I have this database for my game results, and I want it to be sorted by descending time, but on the left i don't want to be like in the picture, I want to go from 1 to 20. How to do that? I placed all these data in a TextView in my xml file.
Here my database class:
public class OffDBHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_SCORE = "score";
private static final String DATABASE_NAME = "highscores";
private static final String DATABASE_TABLE = "highscorestable";
public static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SCORE + " DOUBLE NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public OffDBHelper(Context c){
ourContext = c;
}
public OffDBHelper open() throws Exception{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, double score) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_SCORE, score);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_SCORE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, "score DESC");
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iScore = c.getColumnIndex(KEY_SCORE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iScore) + "\n";
}
return result;
}
}
And my data managing class:
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
OffDBHelper info = new OffDBHelper(this);
try {
info.open();
} catch (Exception e) {
e.printStackTrace();
}
String data = info.getData();
info.close();
tv.setText(data);
This is what you need
TableConstants.Reminders.COLUMN_ONE + " ASC, " +
TableConstants.Reminders.COLUMN_ID + " DESC"
In you case you need to modify
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, "_id ASC,
score DESC");
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_SCORE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, KEY_ROWID +" ASC");// REPLACE WITH ASC AS WELL AS ALSO PUT DEASC FOR DSCEDING
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iScore = c.getColumnIndex(KEY_SCORE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iScore) + "\n";
}
in my case it was query function mistake:
Cursor c = db.query(SEARCH_TABLE_NAME, null, null, null, null, null, null, SEARCH_COUNT + " DESC");
insted of:
Cursor c = db.query(SEARCH_TABLE_NAME, null, null, null, null, null, SEARCH_COUNT + " DESC");
1 arg more then i need...