Select query where day of week? - java

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 + "'";

Related

Update a determinate field in a table

I want to modify a field of a determinate id, in my case the field is notify_datetime.
But when I run the app and try to do that, the app crashes giving this error.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.msnma.movienotifier, PID: 4047
android.database.sqlite.SQLiteException: no such column: notify_datetime (Sqlite code 1): , while compiling: UPDATE MovieTypeTable SET notify_datetime=? WHERE notify_datetime = ?, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:910)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:521)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1856)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1799)
at com.example.msnma.movienotifier.database.MovieDatabase.updateNotifyDate(MovieDatabase.java:299)
at com.example.msnma.movienotifier.adapter.MoviesAdapter$9.onClick(MoviesAdapter.java:445)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
The method is called updateNotifyDate and should modify notify_datetime.
MovieDatabase.java
package com.example.msnma.movienotifier.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.databaseModel.TypeDBModel;
import com.example.msnma.movienotifier.mapper.MovieMapper;
import com.example.msnma.movienotifier.model.Movie;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MovieDatabase extends SQLiteOpenHelper {
private static final String LOG = "DatabaseHelper";
private static final String DATABASE_NAME = "movieDatabase";
private static final int DATABASE_VERSION = 1;
//Table Names
private static final String TABLE_MOVIE = "MovieTable";
private static final String TABLE_TYPE = "TypeTable";
private static final String TABLE_MOVIE_TYPE = "MovieTypeTable";
//Table Fields
private static final String MOVIE_ID ="movie_id";
public static final String TITLE ="title";
private static final String OVERVIEW = "overview";
private static final String POSTER_URL = "posterUrl";
private static final String BACKDROP_URL = "backdropUrl";
private static final String TRAILER_URL = "trailerUrl";
private static final String RELEASE_DATE = "releaseDate";
private static final String RATING = "rating";
private static final String ADULT = "adult";
private static final String TYPE_ID = "type_id";
private static final String TYPE_DESCR = "type_descr";
private static final String MOVIE_TYPE_ID = "movie_type_id";
private static final String M_ID = "movie_id";
private static final String T_ID = "type_id";
private static final String notify_datetime = "notify_datetime";
// Table Create Statements
private static final String CREATE_TABLE_MOVIE = "CREATE TABLE "
+ TABLE_MOVIE + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," + TITLE + " TEXT,"
+ OVERVIEW + " TEXT," + POSTER_URL + " TEXT," + BACKDROP_URL + " TEXT," + TRAILER_URL + " TEXT,"
+ RATING + " REAL," + ADULT + " INTEGER," + RELEASE_DATE + " DATETIME," + notify_datetime + " DATETIME" + ")";
// Tag table create statement
private static final String CREATE_TABLE_TYPE = "CREATE TABLE " + TABLE_TYPE
+ "(" + TYPE_ID + " INTEGER PRIMARY KEY," + TYPE_DESCR + " TEXT" + ")";
// todo_tag table create statement
private static final String CREATE_TABLE_MOVIE_TYPE = "CREATE TABLE "
+ TABLE_MOVIE_TYPE + "(" + MOVIE_TYPE_ID + " INTEGER PRIMARY KEY,"
+ M_ID + " INTEGER," + T_ID + " INTEGER" + ")";
static SQLiteDatabase database;
public MovieDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_MOVIE);
db.execSQL(CREATE_TABLE_TYPE);
db.execSQL(CREATE_TABLE_MOVIE_TYPE);
insertType(db); //NOTA: questo va chiamato solo la prima volta che instanziamo il DB, AGGIUNGERE CONTROLLO!
//in teoria onCreate verrà chiamato solo la prima volta...
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TYPE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE_TYPE);
// create new tables
onCreate(db);
}
//questa funzione serve solo per inserire casualmente dai suggested movies, alcuni notify e watched movies
public static void saveMoviesOnDB(List<Movie> movies, String type){
MovieDatabase db = MainActivity.getMovieDatabase();
MovieMapper mapper = new MovieMapper();
List<MovieDBModel> moviesDB = mapper.toMovieDBModelList(movies);
Integer typeId = 0;
int index = 0;
if(type.equals("notify")){
typeId = 1;
}else if(type.equals("watched")){
typeId = 2;
index = index+5;
}else{
//todo catch invalid type Id exception
}
for(int a = index; a<index+5; a++){
insertMovie(moviesDB.get(a), typeId, db);
}
}
//open the database, maybe not useful...
public MovieDatabase open() throws SQLException
{
database = getWritableDatabase();
return this;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
//CRUDs
public static void insertMovie(MovieDBModel movie, Integer typeId, MovieDatabase db) {
SQLiteDatabase database = db.getWritableDatabase();
if(checkMovieUniqueness(movie.getTitle(), db)) { //NON VOGLIO INSERIRE PIù VOLTE LO STESSO FILM
ContentValues values = new ContentValues();
values.put(TITLE, movie.getTitle());
values.put(OVERVIEW, movie.getOverview());
values.put(POSTER_URL, movie.getPosterUrl());
values.put(BACKDROP_URL, movie.getBackdropUrl());
values.put(TRAILER_URL, movie.getTrailerUrl());
values.put(RELEASE_DATE, movie.getReleaseDate().toString());
values.put(RATING, movie.getRating());
values.put(ADULT, movie.isAdult());
//inizio nuovo codice
if(typeId == 1) {
values.put(notify_datetime, movie.getNotifyDate().toString());
Log.i("TYPEID", "Siamo dentro");
}
//else values.putNull(NOTIFY_TIME_DATE);
//fine nuovo codice
// insert row
long movieId = database.insert(TABLE_MOVIE, null, values);
insertMovieType(movieId, typeId, db);
}
}
public static void insertMovieType(Long movieId, Integer typeId, MovieDatabase db){
SQLiteDatabase database = db.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(M_ID, movieId.intValue());
values.put(T_ID, typeId);
database.insert(TABLE_MOVIE_TYPE, null, values);
}
private void insertType(SQLiteDatabase db){
ContentValues descr1 = new ContentValues();
descr1.put(TYPE_DESCR, "NOTIFY");
ContentValues descr2 = new ContentValues();
descr2.put(TYPE_DESCR, "WATCHED");
// insert row
db.insert(TABLE_TYPE, null, descr1);
db.insert(TABLE_TYPE, null, descr2);
}
private TypeDBModel getTypeByTypeDescr(String typeDescr) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_TYPE + " WHERE "
+ TYPE_DESCR + " = " + typeDescr;
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
TypeDBModel td = new TypeDBModel();
td.setId(c.getInt(c.getColumnIndex(TYPE_ID)));
td.setDescription((c.getString(c.getColumnIndex(TYPE_DESCR))));
return td;
}
private static boolean checkMovieUniqueness(String movieTitle, MovieDatabase db) {
SQLiteDatabase database = db.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " WHERE "
+ TITLE + " = " + "'"+ movieTitle + "'";
Log.e(LOG, selectQuery);
Cursor c = database.rawQuery(selectQuery, null);
if(c.moveToFirst()){
c.close();
return false;
}else{
c.close();
return true;
}
}
public List<MovieDBModel> getAllMovieByType(String typeDescr) throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " mv, "
+ TABLE_TYPE + " type, " + TABLE_MOVIE_TYPE + " tmt WHERE type."
+ TYPE_DESCR + " = '" + typeDescr + "'" + " AND type." + TYPE_ID
+ " = " + "tmt." + T_ID + " AND mv." + MOVIE_ID + " = "
+ "tmt." + M_ID;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
//nuovo codice
String datenotifyString = c.getString(c.getColumnIndex(notify_datetime));
if(datenotifyString != null)
{
Date datenotify = sdf3.parse(datenotifyString);
td.setNotifyDate(datenotify);
}
//fine nuovo codice
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
public void deleteMovie(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE, MOVIE_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public void deleteMovieType(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE_TYPE, M_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public int updateMovieType(long id, long tag_id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(T_ID, tag_id);
// updating row
return db.update(TABLE_MOVIE_TYPE, values, M_ID + " = ?",
new String[] { String.valueOf(id) });
}
//da sistemare.
public int updateNotifyDate(long id, Date datetime ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notify_datetime,datetime.toString());
// updating row
return db.update(TABLE_MOVIE_TYPE, values, notify_datetime + " = ?",
new String[] { String.valueOf(id) });
}
public boolean isEmpty() throws ParseException {
boolean isEmpty = false;
List<MovieDBModel> movie1 = getAllMovieByType("NOTIFY");
List<MovieDBModel> movie2 = getAllMovieByType("WATCHED");
if(movie1.isEmpty() && movie2.isEmpty()){
isEmpty = true;
}
return isEmpty;
}
public static List<MovieDBModel> getAllMovies() throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = database;
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
}
In MoviesAdapter.java only piece that call updateNotifyDate:
MovieDatabase md = new MovieDatabase(context);
Log.i("IDMOVIE","ID:"+movies.get(position).getId());
md.updateNotifyDate(movies.get(position).getId(),datatime);
}
Why it doesn't work? What am I wrong?
You're attempting to update MovieTypeTable but your image suggests the notify_datetime is in MovieTable so it's throwing SQLiteException: no such column.

Android: cannot resolve method "query(java.lang.string)"

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].

Table not created using sqlite in android application

I try to create a table in my database. I am using this framework: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
I have edited the code for a bit. In the code below, a table login is created(correct me if im wrong). But I cant see any table named login in the database.
Here is the complete code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TOTAL_USAGE = "total_usage";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT,"
+ KEY_TOTAL_USAGE + " TEXT);";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// values.put(KEY_TOTAL_USAGE, total_usage); // Total_usage
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Storing user details in database
* */
public void updateUser(String email, String total_usage) {
String selectQuery = "UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(selectQuery);
// Cursor cursor = db.rawQuery(selectQuery, null);
// System.out.print("Count"+cursor.getCount());
/*
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'", null);
db.rawQuery("UPDATE login SET total_usage = 132 WHERE email = 'sampleMail'", null);
db.setTransactionSuccessful();
db.close(); */
// db.rawQuery("UPDATE "+ TABLE_LOGIN + " SET "+ KEY_TOTAL_USAGE +" = " + total_usage + " WHERE " + KEY_EMAIL + " = '" + email + "'", null);
// db.rawQuery("UPDATE "+ TABLE_LOGIN + " SET "+ KEY_TOTAL_USAGE +" = " + total_usage + " WHERE " + KEY_EMAIL + " = '" + email + "'", null);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
This code(see below) from above creates the table login, right?
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT,"
+ KEY_TOTAL_USAGE + " TEXT);";
db.execSQL(CREATE_LOGIN_TABLE);
}
So my question is: why there is no table called login? Or am I misinterpreting something?
If I am doing something wrong, could someone help me solving it?
The application runs correctly(without crashes etc), there is no output at the logcat
Thanks in advance

Android SQLite helper - where should I close the connection?

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();
}

How to create multiple table?

Please help me, I'm newbie and I have problem. I try to create multiple table in this code but always error. this error say there is no table PENGINAPAN and i can't solve it.
this is DatabaseHelper class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS WISATA");
db.execSQL("CREATE TABLE if not exists WISATA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists PENGINAPAN (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Ragunan");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Taman Mini");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Melati");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Villa");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Bintang");
db.insert("PENGINAPAN", NAMA, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("WISATA", null, null);
db.delete("WISATA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("WISATA", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query("PENGINAPAN", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
please help me.
I cleaned up your code. If it doesn't work, uninstall your app and install it again. Be sure you create the database before you try to write/read any data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
private static final String TABLE_WISATA = "WISATA";
private static final String TABLE_PENGINAPAN = "PENGINAPAN";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WISATA);
db.execSQL("CREATE TABLE if not exists " + TABLE_WISATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists " + TABLE_PENGINAPAN + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAMA + " TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Ragunan");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Taman Mini");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Melati");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Villa");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Bintang");
db.insert(TABLE_PENGINAPAN, null, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete(TABLE_WISATA, null, null);
db.delete(TABLE_WISATA, null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query(TABLE_WISATA, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query(TABLE_PENGINAPAN, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Use this code and modify it as per your needs. i have added all comments so that you can understand where i am adding a table, where i am adding a column and where i am adding entries.
public class DatabaseHelper extends SQLiteOpenHelper {
//changing master
// Logcat tag
//add comment
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Table Names
private static final String TABLE_VIDEO = "video";
private static final String TABLE_PICTURE = "pictures";
private static final String TABLE_MUSIC = "music";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_FAV = "fav";
// MUSIC Table - column names
private static final String KEY_MUSIC_PATH = "path";
private static final String KEY_MUSIC_CAT_ID = "cat_id";
private static final String KEY_MUSIC_NAME = "music_name";
// PICTURE Table - column names
private static final String KEY_PICTURE_PATH = "path";
private static final String KEY_PICTURE_CAT_ID = "cat_id";
private static final String KEY_PICTURE_NAME = "picture_name";
// VIDEO Table - column names
private static final String KEY_VIDEO_PATH = "path";
private static final String KEY_VIDEO_CAT_ID = "cat_id";
private static final String KEY_VIDEO_SUBCAT_ID = "subcat_id";
private static final String KEY_VIDEO_NAME = "video_name";
// Table Create Statements
// Video table create statement
private static final String CREATE_TABLE_VIDEO = "CREATE TABLE "
+ TABLE_VIDEO + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_VIDEO_PATH + " TEXT,"
+ KEY_VIDEO_CAT_ID+ " INTEGER,"
+ KEY_VIDEO_SUBCAT_ID + " TEXT,"
+ KEY_VIDEO_NAME + " TEXT)";
// PICTURE table create statement
private static final String CREATE_TABLE_PICTURE = "CREATE TABLE "
+ TABLE_PICTURE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_PICTURE_PATH + " TEXT," + KEY_PICTURE_CAT_ID+ " INTEGER,"
+ KEY_PICTURE_NAME + " TEXT)";
// MUSIC table create statement
private static final String CREATE_TABLE_MUSIC = "CREATE TABLE "
+ TABLE_MUSIC + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_MUSIC_PATH + " TEXT," + KEY_MUSIC_CAT_ID+ " INTEGER,"
+ KEY_MUSIC_NAME + " TEXT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// creating required tables
db.execSQL(CREATE_TABLE_PICTURE);
db.execSQL(CREATE_TABLE_MUSIC);
db.execSQL(CREATE_TABLE_VIDEO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VIDEO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PICTURE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MUSIC);
// create new tables
onCreate(db);
}
/*
* create videos
* */
/* public boolean addVideos(List<Video> video, int category_id){
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
for(int i = 0; i <video.size(); ++i){
ContentValues values = new ContentValues();
values.put(KEY_VIDEO_NAME, video.get(i).getName());
values.put(KEY_VIDEO_PATH, video.get(i).getPath());
values.put(KEY_VIDEO_CAT_ID, category_id);
// insert row
id = db.insert(TABLE_VIDEO, null, values);
}
if (id < 0)
return false;
return true;
}*/
// add videos
public void addvideos(Video item, int catid, String subcat) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (fav, path, cat_id, subcat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + subcat + "'," + "'" + item.getName() + "'" + ")");
}
// add pictures
public void addpictures(Picture item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
// add music
public void addmusic(Music item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
/*
* getting all videos
* */
public List<Video> getAllVideos() {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
/*
* getting all videos by categories
* */
public List<Video> getAllVideosByCategory(String category) {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO +
" WHERE " + TABLE_VIDEO + "." + KEY_VIDEO_SUBCAT_ID +
" = " + category;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all pictures
public List<Picture> getAllPictures() {
List<Picture> lstVideo = new ArrayList<Picture>();
String selectQuery = "SELECT * FROM " + TABLE_PICTURE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Picture video = new Picture();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_PICTURE_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_PICTURE_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all music
public List<Music> getAllMusic() {
List<Music> lstVideo = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_MUSIC;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Music video = new Music();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
}
Updated Answer: Picture class code is added
public class Picture {
public int id;
public String name;
public String path;
public int favourite;
public int getFavourite() {
return favourite;
}
public void setFavourite(int favourite) {
this.favourite = favourite;
}
public Picture(){
}
public Picture(int id, String name, String path){
this.id = id;
this.name = name;
this.path = path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}

Categories