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
Related
hi i am trying to make a raffle table but however i did created the database but no table is create, the run panel shows that i created it but the sqlite browser shows that there is nothing in it.
here is the code:
in the database java:
public void onCreate(SQLiteDatabase db)
{
// Note the use of super, which calls the constructor of the SQLiteOpenHelper class,
// which does the actual work of opening the database.
Log.d(TAG, "DatabaseHelper onCreate");
Log.d(TAG, RaffleTable.CREATE_STATEMENT);
db.execSQL(RaffleTable.CREATE_STATEMENT);
}
in the raffletalbe.java:
public class RaffleTable {
public static final String TABLE_NAME = "Raffle";
public static final String KEY_ID = "raffle_id";
public static final String KEY_NAME = "raffle_name";
public static final String KEY_PRICE = "price";
public static final String KEY_START = "raffle_start";
public static final String KEY_END = "raffle_end";
public static final String KEY_DESCRIPTION = "raffle_description";
public static final String KEY_TYPE = "raffle_type";
public static final String KEY_PRIZE = "raffle_prize";
public static final String KEY_LIMIT = "raffle_limit";
public static final String CREATE_STATEMENT = "CREATE TABLE "
+ TABLE_NAME
+ " (" + KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " string not null, "
+ KEY_DESCRIPTION + " string, "
+ KEY_START + " string not null, "
+ KEY_END + " string not null, "
+ KEY_TYPE + " integer not null, "
+ KEY_LIMIT + " integer, "
+ KEY_PRIZE + " String, "
+ KEY_PRICE + " real);";
what it shows in the run panel:
D/RaffleDatabase: DatabaseHelper onCreate
CREATE TABLE Raffle (raffle_id integer primary key autoincrement, raffle_name string not null, raffle_description string, raffle_start string not null, raffle_end string not null, raffle_type integer not null, raffle_limit integer, raffle_prize String, price real);
here is the code i used to insert the table:
Raffle Ruffle1 = new Raffle();
Ruffle1.setRuffleDes("742 Evergreen Terrace");
Ruffle1.setRuffleEnd("20190102");
Ruffle1.setRuffleStart("20190101");
Ruffle1.setRuffleLimit(5);
Ruffle1.setRuffleName("testing");
Ruffle1.setRufflePrize("cooper");
Ruffle1.setRuffleType("Normal");
Ruffle1.setRufflePrice(1000);
Raffle Ruffle2 = new Raffle();
Ruffle2.setRuffleDes("742 Evergreen Terrace");
Ruffle2.setRuffleEnd("20190102");
Ruffle2.setRuffleStart("20190101");
Ruffle2.setRuffleLimit(5);
Ruffle2.setRuffleName("testing");
Ruffle2.setRufflePrize("cooper");
Ruffle2.setRuffleType("Normal");
Ruffle2.setRufflePrice(1000);
RaffleTable.insert(db, Ruffle1);
RaffleTable.insert(db, Ruffle2);
There is nothing wrong with your code. You just need to put the updated file in your browser. May be your browser is reading the old file that's why you're not able to read the updated content.
I am learing to code and made a stopwatch that saves the laptimes in a String and gets the date as a String as well. I want to put those in a SQLite database (so i can later display the date in a listview and open it in another activity that shows all the laptimes.) I've followed some of the codes on the internet and try to put stuff together so I might look over some things in my code. I've commented on the parts I think i understand so you can follow my thinking a bit.
The problem: when i press save the following code is executed and returns the toastmessage: Somehting went wrong.
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String dateStamp = getCurrentTimeStamp();
AddData(dataInput, dateStamp);
//DatabaseHelper.deleteAll();
}
}); //save data though AddData method as input the listText
The method AddData is as follows:
public void AddData(String time, String date) {
boolean insertData = DatabaseHelper.addData(time, date);
if (insertData) {
toastMessage(dataInput);
} else {
toastMessage("Something went wrong");
}
}
The boolean method in the DatabaseHelper class is this:
public boolean addData(String times, String date) { //addData that takes a string
SQLiteDatabase db = this.getWritableDatabase(); //database called db and use getWritableDatabase method
ContentValues contentValues = new ContentValues(); //make a new object of ContentValues
contentValues.put(COL_2, times); //put COL_2 and the String in the ContentValues object
contentValues.put(COL_3, date);
long result = db.insert(TABLE_NAME, null, contentValues); //insert contentValues object into the table
//if date as inserted incorrectly it will return -1
if (result == -1) {
db.close();
return false;
} else {
return true;
}
}
It works when i input just 1 variable in addData() but not with 2 that I later implemented. I think it should work. Below I also put the code that is used to make the SQLite Database.
public static final String TABLE_NAME = "stopwatch"; //make a table with name
public static final String COL_1 = "ID"; //make an ID for every colomn
public static final String COL_2 = "times"; //make a 2nd colomn for data
public static final String COL_3= "date";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) { //make the onCreate method that takes the database as input
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT" + COL_3 +" TEXT)"; //create the table with SQL statements to input the data correctly
db.execSQL(createTable); //input the SQL statements in the DB
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //make upgrade method that takes the database and the versions
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME); //execute SQL statements drop table and which one
onCreate(db); //run through create method
}
I hope someone can help me to find the problem so I can learn more.
Your create table query is missing a comma after the COL_2 +" TEXT"
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT, " + COL_3 +" TEXT)"; // Added a comma after the COL_2
db.execSQL(createTable);
}
I can see one problem from a quick glance and that is a missing comma in your creation statement which would mean that your database was not created as you intended. Try the below amendment.
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT," + COL_3 +" TEXT)";
So i have this app I'm making for my school project. it has a custom listview with a custom arrayadapter and it's populated by clicking a button. here is the Room class
public class Room {
private int xBtn;
private int _id;
private int roomImage;
private String name;
private String type;
public Room(String name, String type, int roomImage){
this.name = name;
this.type = type;
this.roomImage = roomImage;
}
here is my DBHandling onCreate(), addRoom() and deleteRoom() Methods:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_TYPE + " TEXT " +
");";
db.execSQL(query);
}
public void addRoom(Room room){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, room.getName());
values.put(COLUMN_TYPE, room.getType());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
public void removeRoom(String roomsName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_NAME + "=\"" + roomsName + "\";");
}
My questing is, let say, we have 5 rooms, room1(id=0), room2(id=1) and so on.
and i delete room room3(#2) will the new order become 0,1,3,4 or 0,1,2,3.
if it didn't become 0,1,2,3 , how can i make it work? and if it did become 0,1,2,3 , will the _id in Room itself change as well or will it only be changed in the table? In short, i want the _id in the class Room to adjust itself automatically with the id in the table. how do i make this work?
When you have a primary key auto increment the first entry will be at 0 then 1 them 2 so on on if you update say row at id 1 it stays 1. Now let's say row row gets deleted, but uh oh you need out back in. It will bout be 2 or 3 or wherever is after your last id.
So I guess it is a very common issue, searching the web I found that I am not the only one who faced a such issue and yes I know that there is a question with almost the same title, however that did not help to solve the issue I am facing ... so let's start from the beginning
I am simply trying to insert into a table that I created.
This table has three columns: "id", "name", "value", and was created as following
public static final String TABLE_NAME = "cookie";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VALUE = "val";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_VALUE + "text not null, "
+ COLUMN_NAME + " text not null"
+ ");";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
Now I am trying to insert into this table as following
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, "username");
values.put(MySQLiteHelper.COLUMN_VALUE, username);
long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null, values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
nameValuePair newComment = cursorToNameValuePair(cursor);
cursor.close();
However I am getting this error
table cookie has no column named val
I searched for similar issues online, most of the solution where talking about a change happened to the database so I need to either
1- Un-install the application before trying to run in debugging mode again
2- update the database version from 1 to 3
However that did not help .. So looking forward for your solutions :)
Problem is here
+ COLUMN_VALUE + "text not null, "
into DATABASE_CREATE String. You missed space between column name and column type.
It should be
+ COLUMN_VALUE + " text not null, "
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.