Android SQLite helper - where should I close the connection? - java

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

Related

Android: Throwing error while inserting data in table

I have created 2 tables in a db. 1 is working fine. TABLE_NAME2 is giving error while inserting data in it saying Column Email is not found.
DatabaseHelper.java:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME2 + "("
+ USER_NAME + "TEXT,"
+ USER_EMAIL + "TEXT,"
+ USER_MOBILE + "TEXT, "
+ USER_PASS + "TEXT)");
db.execSQL("CREATE Table " + TABLE_NAME1 + "("// + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL2 + " TEXT,"
+ COL3 + " TEXT,"
+ COL4 + " TEXT,"
+ COL5 + " TEXT,"
+ COL6 + " TEXT,"
+ COL7 + " TEXT)");
}
public boolean insertSignupDataDB(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_NAME, name);
contentValues.put(USER_EMAIL, email);
contentValues.put(USER_MOBILE, mobile);
contentValues.put(USER_PASS, pass);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
Log:
(1) table signup has no column named EMAIL
06-08 21:00:51.306 15019-15019/com.mgm.manish.trekcompanion E/SQLiteDatabase: Error inserting EMAIL=abc NAME=abc PASSWORD=abc MOBILE=abc
android.database.sqlite.SQLiteException: table signup has no column named EMAIL (code 1): , while compiling: INSERT INTO signup(EMAIL,NAME,PASSWORD,MOBILE) VALUES (?,?,?,?)
Please solve this
From this page I am sending data to DatabaseHelper Class to insert data.
It shows the toast "successful signup", but is showing error in Logs, and also it is not navigating to LoginActivity class. it is navigating to MainActivity.
Even else part is not working. when i put different passwords it gives error app stopped.
if(etSignPass.getText().toString().equals(etSignConPass.getText().toString())){
boolean queryResult = dbHelper.insertSignupDataDB(etSignName.getText().toString(),
etSignEmail.getText().toString(), etSignMobile.getText().toString(), etSignPass.getText().toString());
if(queryResult=true){
Toast.makeText(SignUp.this, "Successfully Signed up", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
navigateUpTo(new Intent(SignUp.this,LoginActivity.class));
}
}
else{
Toast.makeText(SignUp.this, "Error", Toast.LENGTH_SHORT).show();
}
}
else{
etSignConPass.setBackgroundColor(Color.RED);
onClicSignUp();
}
}
This is complete code of DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "abc.db";
public static final String TABLE_NAME1 = "table1";
public static final String COL2 = "col1";
public static final String COL3 = "Date";
public static final String COL4 = "Cost";
public static final String COL5 = "loc1";
public static final String COL6 = "loc2";
public static final String COL7 = "Description";
public static final String TABLE_NAME2 = "signup";
public static final String USER_NAME = "NAME";
public static final String USER_EMAIL = "EMAIL";
public static final String USER_MOBILE = "MOBILE";
public static final String USER_PASS = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME2 + "("
+ USER_NAME + "TEXT,"
+ USER_EMAIL + "TEXT,"
+ USER_MOBILE + "TEXT, "
+ USER_PASS + "TEXT)");
db.execSQL("CREATE Table " + TABLE_NAME1 + "("// + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL2 + " TEXT,"
+ COL3 + " TEXT,"
+ COL4 + " TEXT,"
+ COL5 + " TEXT,"
+ COL6 + " TEXT,"
+ COL7 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME1);
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME2);
onCreate(db);
}
public boolean insertHomeDataDB(String locName, String date, String cost, String startLoc, String endLoc, String description){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, locName);
contentValues.put(COL3, date);
contentValues.put(COL4, cost);
contentValues.put(COL5, startLoc);
contentValues.put(COL6, endLoc);
contentValues.put(COL7, description);
//contentValues.put(COL8, userId);
long result = db.insert(TABLE_NAME1, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
public boolean insertSignupDataDB(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_NAME, name);
contentValues.put(USER_EMAIL, email);
contentValues.put(USER_MOBILE, mobile);
contentValues.put(USER_PASS, pass);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
public Cursor getAllHomeData(SQLiteDatabase db){
Cursor res;
String[] projection = {COL2,COL3,COL4};
res = db.query(TABLE_NAME1,projection,null,null,null,null,null);
return res;
}
public Cursor getAllProfileData(SQLiteDatabase db){
Cursor res;
String[] projection={USER_NAME,USER_EMAIL,USER_MOBILE,USER_PASS};
res = db.query(TABLE_NAME2, projection,null,null,null,null,null);
return res;
}
}

android.database.sqlite.SQLiteException near ")"

Can anyone see what is wrong with this code please, this is the error given:
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE scores(_id INTEGER PRIMARY KEY AUTOINCREMENT , scoreName TEXT , );
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "scores.db";
public static final String TABLE_SCORES = "scores";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SCORENAME = "scoreName";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_SCORES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_SCORENAME + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_SCORES);
onCreate(db);
}
public void addScore(Scores score) {
ContentValues values = new ContentValues();
values.put(COLUMN_SCORENAME, score.get_scoreName());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_SCORES, null, values);
db.close();
}
public void deleteScore(String scoreName) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SCORES + "WHERE " + COLUMN_SCORENAME + "=\"" + scoreName + "\";");
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SCORES + "WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//move to first row in your results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("scoreName")) != null) {
dbString += c.getString(c.getColumnIndex("scoreName"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Seems problem in Query for creating table (comma is missing after AUTOINCREMENT). Try this
db.execSQL("CREATE TABLE " + TABLE_SCORES + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_SCORENAME + " TEXT" + ");");

Select query where day of week?

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

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

How to sort SQLite data by _id AND by another column

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

Categories