I'm using SQLite to create a database table for my app. I've searched online but haven't found the answer yet: Do I need to create a database first or is there a default database for each app?
I've written the following DBHelper class. It's in a separate file. How Do I call it when the app starts?
public class DataBaseHelper extends SQLiteOpenHelper{
final String CREAT_TABLE = "CREATE TABLE IF NOT EXIST `employee` ("+
"`id` int(11) NOT NULL AUTO_INCREMENT,"+
"`firstName` varchar(30) NOT NULL,"+
"`lastName` varchar(30) NOT NULL,"+
"PRIMARY KEY (`id`)"+
") ;";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREAT_TABLE);
}
}
You don't have to create the database yourself.
You specify the database name (the sqlite file name) when you call the superconstructor of your open helper.
This will create or update the database with that name when needed (depending on which version number you send in vs. the current version number meta data).
I don't know what your constructor looks like but let's say it looks like
public DatabaseHelper(final Context context) {
super(context, "mydatabase", null, 0);
}
Then the SQLiteOpenHelper will create a database named "mydatabase" when you call getReadableDatabase() or getWritableDatabase(). It's all in the docs.
You declare your database name in the constructor
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Related
So I am trying to create a Database and a table in android studio. The database is created successfully but table is not creating when I am using my android phone but both the database and the table are created when I use Virtual device from the AVD.
public class Databases extends SQLiteOpenHelper {
public static final String dbname = "AttendanceDb11";
public Databases(#Nullable Context context) {
super(context, dbname, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE Student12 ( _id INTEGER PRIMARY KEY AUTOINCREMENT, Name Text)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("Drop table if exists Student12");
onCreate(db);
}
}
Here is my code
It looks like that app was already installed before you created the tables. I would do one of the following:
1: Uninstalling and re-installing the app.
2: The best and better approach is to drop and recreate table in onUpdate method, and increase the db version whenever you change the schema.
I am attempting to create a database in my Android app. It has worked, but when I restart the emulator I receive an error that indicates that my table does not exist. I have found that my "OnCreate" is not started and there is no directory on my sd card of my app? Can you help me find my mistake?
My code is:
public DatabaseVerwerker(Context context) {
super(context, database_naam, null, database_version);
}
public void onCreate(SQLiteDatabase db)
db.execSQL("CREATE TABLE IF NOT EXISTS variabel (key TEXT, value TEXT);");
)
And will the database still exists after close and open the app?
Greatings,
I hope it's my last post of android. it get's to mutch
Make sure your database has been created before you do your operation on database. The better way to create a database only used by your application is using openOrCreateDatabase. Here is the example.
CursorFactory cursorFactory = new CursorFactory() {
#Override
public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,
String editTable, SQLiteQuery query) {
return null;
}
};
openOrCreateDatabase(DBNAME, MODE_PRIVATE, cursorFactory, new DatabaseErrorHandler() {
#Override
public void onCorruption(SQLiteDatabase dbObj) {
}
})
Thanks it works again. i must build the onUpdate function and trigger it.
Is it better to have a single big SQLiteOpenHelper subclass that defines onCreate and onUpgrade methods for every table in the database, or is better to have many SQLiteOpenHelper subclasses, one for each table?
Is there a best practice? Or are both acceptable, but with different good and bad side effects?
You should have a single SQLiteOpenHelper class for all the tables. Check this link.
Just for the sake of a different approach:
You can always overried on the onOpen(..) method have it called your onCreate(..) . Be sure to use the "CREATE TABLE IF NOT EXISTS..." statement rather than "CREATE TABLE"
#Override
public void onOpen(SQLiteDatabase db) {
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FRIENDS_TABLE = "CREATE TABLE IF NOT EXISTS ...";
db.execSQL(CREATE_FRIENDS_TABLE);
}
You do that with every class that extends from SQLiteOpenHelper
#TheReader is right. I prefer a single SQLiteOpenHelper for all tables, here is what i do: pass a List of "table creation" sqls to the Constructor of the SQLiteOpenHelper subClass, then in the onCreate function iterate the list to create each table.
so my SQLiteOpenHelper subclass looks sth like this:
public ModelReaderDbHelper(Context context, List<String> createSQLs, List<String> deleteSQLs){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.TABLE_CREATION_SQLS = createSQLs;
this.TABLE_DELETE_SQLS = deleteSQLs;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
for(String oneCreation : TABLE_CREATION_SQLS){
sqLiteDatabase.execSQL(oneCreation);
}
}
But that comes another problem: after adding a new table, and install the new version of the app with an existing old one installed, the new table won't be created, because the existence of the old database will prevent the onCreate function from being called. So user has to uninstall the app first, and install the app completely. The DATABASE_VERSION helps, it seem android will not execute the onCreate function if and only if the a existin database with the same name and the same DATABASE_VERSION
I am learning to use Sqlite on Android by using this tutorial. I am having trouble understanding some of the code.
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// 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_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
I make a new object of DatabaseHandler in my activity. The super in the constructor is SQLiteOpenHelper constructor. The code works great, it creates a new database, if there is none and it uses the old one if it exists. I would like to make some changes to this code(I want to add different tables to one db), but I dont understand how exactly does this work, how does the constructor know if it should create a new db or use the existing one?
The trick is that your class extends SQLiteOpenHelper, the call to super in your constructor triggers a lot of behind-the-scenes code.
If you read through the SQLiteOpenHelper source code you'll see that getWritableDatabase() and getReadableDatabase() call the same method: SQLiteOpenHelper#getDatabaseLocked(). This method does most of the work. It is the one that determines whether a database needs to be created, opened, upgraded, or anything else, from the information that you supplied in one simple command: super(context, DATABASE_NAME, null, DATABASE_VERSION);.
When you want to open your db, you call SQLiteOpenHelper.getReadableDatabase() or SQLiteOpenHelper.getWriteableDatabase(). If the database exists, these return a handle to it. If it doesn't exist, the system calls onCreate(), where you do the db.execSQL.
It would be better to call the class DatabaseOpenHelper instead of DatabaseHandler. What it does is defer creating the database until its needed, instead of creating it at the beginning of some other class. This is particularly useful for content providers backed by an SQLite database. You should use ContentProvider.onCreate() to do very quick initialization, and then implement SQLiteOpenHelper.onCreate() to create the database. That way, the system can load your ContentProvider when your app starts, but it doesn't have to do anything with your database until something tries to access it.
I am writing an app that displays fun-facts (and the source they are from). The user can browse through the facts one by one.
Here is the design I thought of :
Create a table in SQLiteDatabase with a text column that stores the fun-fact and a second column that stores it's source. (not sure if this is the best way to go about doing it, but I want the app available even without the network)
My question is, when database is initially created on the device, should I manually populate the database from within the code, something like this pseodo-code:-
#Override
public void onCreate(SQLiteDatabase db) {
//Create the table
//Populate the table
//Insert statement 1
//Insert statement 2
//Insert statement 3
...
//Insert statement 500
}
Surely there must be a better method to create the initial database when the app is installed?
Are you certain that you really need a databse? Doesn't it just add unnecessary overhead to something so trivial?
Can't you just declare the array in your code, or am I missing something? Whether it's in the db or your code, it is taking up space. The db will add some overhead to that and vious?will take some time to load, plus your code has to handle errors, etc.
Woudl you not be better off with a simple array declared in your code? Or am I misisng something obvious? (maybe users can d/l a new db? But is that so much more overhead than d/ling a new program?)
If I'm way off, please explain (rather than downvoting). I am trying to help
Edit: presumably you already have your facts soemwhere? Maybe in a text file? You could just write code to parse that and initialze and array (or populate a db). It should bascially be a short for loop.
use a class derived from SQLiteOpenHelper
i already wrote sth obout this on my blog www.xenonite.net
public class myDatabase extends SQLiteOpenHelper
{
private static final String DB_NAME = "database.db";
private static final int DB_VERSION = 1;
public MyDatabase(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE tbl_test ( id INTEGER PRIMARY KEY AUTOINCREMENT, test TEXT NOT NULL )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS tbl_test");
onCreate(db);
}
}
you can use this like
myDatabase db = new myDatabase(getApplicationContext());
sql = "INSERT INTO tbl_test (test) VALUES ('xyz')";
db.getWritableDatabase().execSQL(sql);
String sql = "SELECT id FROM tbl_test";
Cursor result = db.getWritableDatabase().rawQuery(sql, null);
int value;
while(result.moveToNext())
{
value = result.getInt(0);
}
on every call to db, myDatabase.onCreate() is called, so your database will be created on the first run. when changing the table structure, implement onUpgrade() and increment DB_VERSION