I'm trying to insert the values from a date picker and a time pickers in my sqlite database. I have stored the date and time in object variables and then call a method in my DBhandler class to insert them through a contentvalue object.
Now where I'm failing here is with the actual insertion and data types.
I'm getting an error on the following code for the 'timeApp' and 'dateApp' I'm passing these variables to the createAppointmentEntry' method as DATE and TIME variables.:
Error message:
The method put(String, String) in the type ContentValues is not applicable for the arguments (String, Time)
Method the errors occuring on:
public void createAppointmentEntry(String nameApp, String typeApp, Time timeApp, Date dateApp ,String commentApp, Boolean onOrOff) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAMEAPP, nameApp);
cv.put(KEY_TYPEAPP, typeApp);
//ERROR on the following two 'puts'
cv.put(KEY_TIMEAPP, timeApp);
cv.put(KEY_DATEAPP, dateApp);
cv.put(KEY_COMMENTAPP, commentApp);
cv.put(KEY_ALARM, onOrOff);
ourDatabase.insert(DATABASE_TABLE, null, cv);
Heres my DB columns:
public static final String KEY_ROWAPPID = "_appid";
public static final String KEY_NAMEAPP = "app_name";
public static final String KEY_TYPEAPP = "app_type";
public static final String KEY_TIMEAPP = "app_time";
public static final String KEY_DATEAPP = "app_date";
public static final String KEY_COMMENTAPP = "app_comments";
public static final String KEY_ALARM = "app_alarm";
My onCreate method:
db.execSQL("CREATE TABLE " + DATABASE_TABLEAPP + " (" +
KEY_ROWAPPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAMEAPP + " TEXT NOT NULL, " +
KEY_TYPEAPP + " TEXT NOT NULL, " +
KEY_TIMEAPP + " TEXT NOT NULL, " +
KEY_DATEAPP + " TEXT NOT NULL, " +
KEY_COMMENTAPP + " TEXT NOT NULL, " +
KEY_ALARM + "BOOLEAN NOT NULL);"
);
Heres how I am setting the time and date object variables:
Date setDate = new Date(dobYear - 1900, dobMonth, dobDate);
Time timeToSet = new Time();
timeToSet.set(0, dobMinute, dobHour);
Judging from the compilation error and the API of ContentValues, it seems that ContentValues only supports primitive types, String and byte[]. So, try replacing:
//ERROR on the following two 'puts'
cv.put(KEY_TIMEAPP, timeApp);
cv.put(KEY_DATEAPP, dateApp);
with:
cv.put(KEY_TIMEAPP, timeApp.toString());
cv.put(KEY_DATEAPP, dateApp.toString());
You can use formatter to format the Time and Date to a standard String to be able to parse it back.
i guess something but i am not sure
KEY_ALARM + "BOOLEAN NOT NULL);"
you missed a whitespace at the create Statement. Try droping it and recreate it same just with the whitespace.
db.execSQL("CREATE TABLE " + DATABASE_TABLEAPP + " (" +
KEY_ROWAPPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAMEAPP + " TEXT NOT NULL, " +
KEY_TYPEAPP + " TEXT NOT NULL, " +
KEY_TIMEAPP + " TEXT NOT NULL, " +
KEY_DATEAPP + " TEXT NOT NULL, " +
KEY_COMMENTAPP + " TEXT NOT NULL, " +
KEY_ALARM + " BOOLEAN NOT NULL);"
KEY_ALARM + " BOOLEAN NOT NULL);"
Made the same misstage yesterday.
if you wrote a Helperclass just change the DATABASE_VERSION Else call the db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLEAPP);
the Helper class would call this for example
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLEAPP);
onCreate(db); //recreate
}
Automaticaly recreate the database with the new statement than.
Related
I get from "SQLiteLog: (1) near "Name": syntax error" after the addPatient() method is called and the data given by addPatient() method is not stored in the database.
At first, I suspect that something might be wrong with my "CREATE TABLE" query but I have tried everything and I couldn't figure out what was wrong.
#Override
public void onCreate(SQLiteDatabase db)
{
//===============Create a table for Patient
String query = "CREATE TABLE TABLE_PATIENT (COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"COLUMN_USERNAME TEXT, " +
"COLUMN_PASSWORD TEXT, " +
"COLUMN_FIRSTNAME TEXT, " +
"COLUMN_LASTNAME TEXT, " +
"COLUMN_AGE TEXT, " +
"COLUMN_GENDER TEXT, " +
"COLUMN_PHONE TEXT, " +
"COLUMN_ADDRESS TEXT);";
db.execSQL(query);
}//End of onCreate()
//Add a new Patient Row to the database
public void addPatient(Patient patient)
{
Log.i(TAG, "addPatient("+patient.getUserName()+")");
ContentValues values = new ContentValues();
values.put(COLUMN_ID, patient.getU_Id());
values.put(COLUMN_USERNAME, patient.getUserName());
values.put(COLUMN_PASSWORD, patient.getPassword());
values.put(COLUMN_FIRSTNAME, patient.getFirstName());
values.put(COLUMN_LASTNAME,patient.getLastName());
values.put(COLUMN_AGE, patient.getAge());
values.put(COLUMN_GENDER,patient.getGender());
values.put(COLUMN_PHONE,patient.getPhoneNumber());
values.put(COLUMN_ADDRESS, patient.getAddress());
SQLiteDatabase db = getWritableDatabase();
try
{
db.insert(TABLE_PATIENT, null, values);
db.close();
}catch (Exception e)
{
Log.i(TAG, e.getMessage());
}
}//End of addPatient()
I guess you have defined these variables:
String COLUMN_ID = "id";
String COLUMN_USERNAME = "username";
....................................
or something like that.
If you have spaces in the names of the columns you must use square brackets or backticks around them, like:
String COLUMN_USERNAME = "[user name]";
In your CREATE TABLE statement you define the column names as:
"COLUMN_ID", "COLUMN_USERNAME", ....
because you use the variable names and not their values.
But in addPatient() method you are putting values to the ContentValues object by using their actual names.
To solve your problem, 1st uninstall the app from the device you are testing it, so the database is deleted.
Then change the CREATE TABLE statement like this:
String query = "CREATE TABLE " + TABLE_PATIENT +" (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_FIRSTNAME + " TEXT, " +
COLUMN_LASTNAME + " TEXT, " +
COLUMN_AGE + " TEXT, " +
COLUMN_GENDER + " TEXT, " +
COLUMN_PHONE + " TEXT, " +
COLUMN_ADDRESS + " TEXT)";
and rerun to recreate the database with the correct column names.
contactid = 123;
SYNC_SUCCESS = 1;
db.updateSyncStatus(contactid, SYNC_SUCCESS);
I have tried the 3 possible ways to update the table in SQLite DB. But its not working. INSERT and DELETE process are working good. Only I am facing problem in the UPDATE. Did I missed anything?
public void updateSyncStatus(String contactid, int syncSuccess) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put(CONTACTS_SYNC_STATUS, syncSuccess);
try {
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + "='" + contactid + "'", null); // Tried, Not working
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID +" = ?", new String[] {contactid}); // Tried, Not Working
db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + " = ?", new String[]{contactid});
}
catch (Exception e){
String error = e.getMessage().toString();
Log.e(TAG, "UpdateError: " + error);
}
db.close();
}
Table Structure:
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("
+ CONTACTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ CONTACTS_NUMBER + " VARCHAR,"
+ CONTACTS_CONTACTID + " VARCHAR,"
+ CONTACTS_SYNC_STATUS + " TINYINT DEFAULT 0" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
Actually the problem is not with the update query. The problem is , before executing the updateSyncStatus method, next statement ran and I am getting the output before updating the rows. So I have used the Handler to wait for 10 seconds before showing the output.
I'm trying to convert a csv file that I get online and try to call a execSQL(String) based on the results.
The only problem is dat I send my SQLiteDatabase with my function in the parameter, but that way I can't acces it from within my resultReady(String result){} if I don't make the parameter final.
But when I make the SQLiteDatabase parameter final, I get the error message:
"attempt to re-open an already-closed object: SQLiteDatabase: ..."
Does anyone know how I could fix this?
The function:
private void insertTalen(SQLiteDatabase db) {
// lijst van alle talen met taalcode opgehaald van het internet
HttpReader httpReader = new HttpReader();
httpReader.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
#Override
public void resultReady(String result) {
CsvHelper csvHelper = new CsvHelper();
List<Taal> talen = csvHelper.getTalenFromCsv(result);
for (Taal taal: talen) {
String SQLScript = "INSERT INTO taal (engelseTaalNaam, taalCode) VALUES ('";
SQLScript += taal.getEngelseNaam();
SQLScript += "', '";
SQLScript += taal.getTaalCode();
SQLScript += "');";
db.execSQL(SQLScript);
}
}
});
httpReader.execute("https://raw.githubusercontent.com/datasets/language-codes/master/data/language-codes.csv");
}
And this function is called from my oncreate:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_TAAL = "CREATE TABLE taal (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"engelseNaam TEXT," +
"taalCode TEXT)";
db.execSQL(CREATE_TABLE_TAAL);
String CREATE_TABLE_GEBRUIKER = "CREATE TABLE gebruiker (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"highscoreGebruikerId INTEGER," +
"eigenTaalId INTEGER," +
"vreemdeTaalId INTEGER," +
"FOREIGN KEY (eigenTaalId) REFERENCES taal(id)," +
"FOREIGN KEY (vreemdeTaalId) REFERENCES taal(id))";
db.execSQL(CREATE_TABLE_GEBRUIKER);
String CREATE_TABLE_OPGESLAGEN_WOORD = "CREATE TABLE opgeslagenWoord (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"taalId INTEGER," +
"naam TEXT," +
"engelseVersieId INTEGER," +
"FOREIGN KEY (taalId) REFERENCES taal(id)," +
"FOREIGN KEY (engelseVersieId) REFERENCES opgeslagenWoord(id))";
db.execSQL(CREATE_TABLE_OPGESLAGEN_WOORD);
String CREATE_TABLE_GEKEND_WOORD = "CREATE TABLE gekendWoord (" +
"opgeslagenWoordId INTEGER PRIMARY KEY ," +
"datumverloopt TEXT," +
"niveauGekend INTEGER," +
"FOREIGN KEY (opgeslagenWoordId) REFERENCES opgeslagenWoord(id))";
db.execSQL(CREATE_TABLE_GEKEND_WOORD);
this.db = db;
insertTalen(db);
insertGebruiker(db);
}
I want to store constructors or references to constructors in an SQL table to look up a class name and be able to access a constructor and instantiate from there. In C I would just store a pointer to a static function; how do I do it in Java? Any ideas?
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_CONSTRUCTOR + " ///SOMETHING THAT CAN DESCRIBE A CONSTRUCTOR///" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 8 years ago.
I need to create a database with 3 tables and I am doing this like below:
public class DatabaseUtils extends SQLiteOpenHelper {
private final Context myContext;
private SQLiteDatabase DataBase;
// Database creation sql statement
private static final String CREATE_TABLE_CS = "create table "+ TABLE_CS + "(" + COLUMN_CS + " TEXT NOT NULL, " + COLUMN_CE_CID + " INTEGER NOT NULL, "+ COLUMN_CE_PID +" INTEGER NOT NULL);";
private static final String CREATE_TABLE_SS = "create table "+ TABLE_SS + "(" + COLUMN_SS + " TEXT NOT NULL, " + COLUMN_SUB_CID + " INTEGER NOT NULL, "+ COLUMN_SUB_PID +" INTEGER NOT NULL);";
private static final String CREATE_TABLE_AS = "create table "+ TABLE_AS + "(" + COLUMN_AS + " TEXT NOT NULL, " + COLUMN_CID + " INTEGER NOT NULL, "+ COLUMN_AID +" INTEGER NOT NULL);";
public DatabaseUtils(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
DATABASE_PATH = Environment.getDataDirectory().getAbsolutePath() + "/" +"data/"+ context.getResources().getString(R.string.app_package);
this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_TABLE_CS);
database.execSQL(CREATE_TABLE_SS);
database.execSQL(CREATE_TABLE_AS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseUtils.class.getName(),"Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
//db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}
}
and in my Activity I am calling DatabaseUtils class in onCreate as below:
DatabaseUtils db = new DatabaseUtils(this);
but Database is not creating with the 3 tables. What am I doing wrong? BTW, I have all the string values correctly. Please help me how to create database.
I found the solution. DatabaseUtils' onCreate() is never called if i implement like below:
DatabaseUtils db = new DatabaseUtils(this);
in myActivity's onCreate() method. I need to call getWritableDatabase() in myActivity as below:
DatabaseUtils db = new DatabaseUtils(this);
db.getWritableDatabase();
Then DatabaseUtils' onCreate() will be called and tables are created.
private void db_ini_create_table(android.database.sqlite.SQLiteDatabase db){
String str_sql = "create table [possible_know_persions] ("+
"[id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+
"[adate] DATETIME DEFAULT (datetime('now','localtime')) NOT NULL,"+
"[current_userid] INTEGER DEFAULT 0 NOT NULL ,"+
"[stranger_user_id] INTEGER DEFAULT 0 NOT NULL ,"+
"[common_friend_count] INTEGER DEFAULT 0 NOT NULL ,"+
"[common_game_count] INTEGER DEFAULT 0 NOT NULL ,"+
"[user_account_type] INTEGER DEFAULT 0 NOT NULL ,"+
"[verify_type] INTEGER NULL "+
");";db.execSQL(str_sql);
str_sql = "CREATE INDEX [possible_stranger_user_id] on [possible_know_persions] ("+"[stranger_user_id] asc "+");";db.execSQL(str_sql);
}
this is a example for your reference