SQL database Columns error, or does not exist? - java

I am working on my sqldatabase, but i cannot move on because my program is giving me an error that there is no such column, even though the column is clearly defined at the top of my code under "KEY_NAME" If anybody can help me or needs me to post anymore code please tell me Thanks!
I've only posted my database.
******* recent logcat information
03-14 01:24:54.285: E/Database(26073): android.database.sqlite.SQLiteException: table PeopleTable has no column named persons_name: , while compiling: INSERT INTO PeopleTable(persons_hotness, persons_name) VALUES(?, ?);
public class HotOrNot {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_HOTNESS = "persons_hotness";
private static final String DATABASE_NAME = "HotOrNotDB";
private static final String DATABASE_TABLE = "PeopleTable";
private 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) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_HOTNESS + " TEXT NOT NULL);");
// String sql = String.format("create table %s "
// + "(%s int primary key, %s int, %s text, %s text)",
// DATABASE_TABLE, KEY_ROWID, KEY_NAME, KEY_HOTNESS);
// db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public HotOrNot(Context c) {
ourContext = c;
}
public HotOrNot open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_HOTNESS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iHotness) + "\n";
}
return result;
}
}

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,KEY_NAME TEXT NOT NULL, " + KEY_HOTNESS + " TEXT NOT NULL);");
Try the above changes..I think the problem might be due to space added before KEY_NAME. Hope this helps u..

try replacing + "KEY_NAME" + with + KEY_NAME + (without double quotes). This line is inside public void onCreate(SQLiteDatabase db)

replace your db.execSQL query by this
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_HOTNESS + " TEXT NOT NULL);");

Related

How to check that a string being entered isn't a unique string. Java (SQLite database)

Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.
Here is my code for the database so far.
public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "appointments.db";
public static final String TABLE_APPOINTMENTS = "appointments";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_MONTH = "month";
public static final String COLUMN_YEAR = "year";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_DESCRIPTION = "details";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_APPOINTMENTS
+ "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
+ COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_APPOINTMENTS);
onCreate(db);
}
public void addAppointment(Appointment app){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
Call this method and check return true mean its exist otherwise not.
public boolean checkAppointmentExist(String name){
booolean isExist = false;
String selection = COLUMN_TITLE + " = ? ";
String[] selectionArgs = new String[]{name};
Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
}
return isExist;
}
public void addAppointment(Appointment app){
if(!checkAppointmentExist(app.get_title())){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}

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

SQLLite Android table not acknowledging database changes - "no such column: type (code 1):"

I am trying to add a key to my SQLite DB but when I try to access the new column, the program throws "no such column type (code 1)". I verified in SQLite Editor that the new column is in fact present. Am I missing something?
SOLUTION FOUND
My Database creation was NOT taking in the DATABASE_VERSION, I had simply set it to use "1". As soon as I set it to use that variable, and changed it from 1 to 2, it updated my database!
Here is my class
package com.example.blizz_000.lureorganizer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
public class LureOrganizer {
public com.example.blizz_000.lureorganizer.DatabaseHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public static final String KEY_NAME = "model";
public static final String KEY_MAKER = "company";
public static final String KEY_SIZE = "size";
public static final String KEY_COLOR = "color";
public static final String KEY_TYPE = "TEST";
public static final String KEY_ROWID = "_id";
private static final String DATABASE_NAME = "fishing_db";
private static final String DATABASE_TABLE = "LURES";
public static int DATABASE_VERSION = 1;
// DATABASE HELPER CLASS*********************************************************
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(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, " +
KEY_MAKER + " TEXT, " +
KEY_COLOR + " TEXT, " +
"TEST text, " +
KEY_SIZE + " TEXT);");
//db.execSQL("ALTER TABLE LURES ADD COLUMN TEST TEST"); // Won't find the table
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
// END DATABASE HELPER CLASS *********************************************************
//*********************BEGIN MY METHODS**************************
public LureOrganizer(Context c) {
ourContext = c;}
//Opens Db
public LureOrganizer open() throws SQLException{
ourHelper = new com.example.blizz_000.lureorganizer.DatabaseHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;}
//Opens Db NO EXCEPTION
public LureOrganizer opennoe() {
ourHelper = new com.example.blizz_000.lureorganizer.DatabaseHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;}
//Closes Db
public void close() {
ourHelper.close();}
//Entries
public long createEntry(String name, String maker, String color, String size, String type) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_MAKER, maker);
cv.put(KEY_COLOR, color);
cv.put(KEY_SIZE, size);
cv.put(KEY_TYPE, type);
return ourDatabase.insert(DATABASE_TABLE, null, cv);}
//RETRIEVE ALL PIECES OF THE DATA *****************************************************************************************************//
//Retrive Data for SINGLE PIECE
public String[] getData(String id) {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_MAKER, KEY_COLOR, KEY_SIZE};
Cursor d = ourDatabase.rawQuery("select * from LURES WHERE _id = ?",
new String[]{id});
String[] resultarray = new String[5];
int iName = d.getColumnIndex(KEY_NAME);
int iMaker = d.getColumnIndex(KEY_MAKER);
int iColor = d.getColumnIndex(KEY_COLOR);
int iSize = d.getColumnIndex(KEY_SIZE);
int iType = d.getColumnIndex(KEY_TYPE);
for (d.moveToFirst(); !d.isAfterLast(); d.moveToNext()) {
resultarray[0] = d.getString(iMaker);
resultarray[1] = d.getString(iName);
resultarray[2] = d.getString(iColor);
resultarray[3] = d.getString(iSize);
resultarray[4] = d.getString(iType);
}
return resultarray;
}
//Retrieve Data
public String[] getName() {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_MAKER, KEY_COLOR, KEY_SIZE, KEY_TYPE};
Cursor d = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result ="";
String[] resultarray = new String[5];
int iRow = d.getColumnIndex(KEY_ROWID);
int iName = d.getColumnIndex(KEY_NAME);
int iMaker = d.getColumnIndex(KEY_MAKER);
int iColor = d.getColumnIndex(KEY_COLOR);
int iSize = d.getColumnIndex(KEY_SIZE);
int iType = d.getColumnIndex(KEY_TYPE);
for(d.moveToFirst(); !d.isAfterLast(); d.moveToNext()){
resultarray[0] = d.getString(iMaker);
resultarray[1] = d.getString(iName);
resultarray[2] = d.getString(iColor);
resultarray[3] = d.getString(iSize);
resultarray[4] = d.getString(iType);
}
return resultarray;
}
//CURSOR READER
public Cursor readEntry() {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_MAKER, KEY_COLOR, KEY_SIZE, KEY_TYPE};
Cursor d = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
return d;
}
public void DeleteRow(String id) {
ourDatabase.delete(DATABASE_TABLE, "_id = ?",
new String[]{id});
}
}
I know that the code works other than the KEY_TYPE stuff, so I don't feel it is necessary to include other classes, but I will if it helps.
When you change your database structure (i.e.: altering a table), you have to inform it that your db has changed.
This is done by setting the DATABASE_VERSION constant to a higher value, i.e.: 2.
So:
public static int DATABASE_VERSION = 2;
This will let the onUpgrade() method fire and recreate the table.
And you miss a space after KEY_ROWID:
db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT, " + KEY_MAKER + " TEXT, " +
KEY_COLOR + " TEXT, " + "TEST text, " + KEY_SIZE + " TEXT)");
Whenever you are creating the object to Database open helper it wont call onCreate of that class. only first time that too when you call getWritableDatabse() or getReadableDatabase() at that time only it will call if the database file not exist in your application. why i am saying this because you have written some alter command over there.
If you run the application with out uninstalling at that time database file will not be deleted so it wont call oncreate of that class.
while writing database related code better to uninstall and run the application.
and you are missing one space after the id coloumn.
db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT, " +
KEY_MAKER + " TEXT, " +
KEY_COLOR + " TEXT, " +
"TEST text, " +
KEY_SIZE + " TEXT);");
I hope this will help you.

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