Android Database Locate Data Before Application Starts - android

I need only select operation. Therefore the data should be inserted before the application starts. What is the best way to do this?

Use an subclass of SQLiteOpenHelper to access your db. The onCreate will be called once, when the database is created.
To use your db you can then do:
DBHelper db = new DBHelper(context);
db.getReadableDatabase().query(....);
db.close();
To extend SQLiteOpenHelper do something like (the sql for the table creation is not tested!):
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final Integer DATABASE_VERSION = 1;
DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/*
* Called ONCE on the very first db access (when the db file is created)
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE mytable (_id PRIMARY KEY AUTOINCREMENT, value TEXT); \n" +
"INSERT INTO mytable (value) VALUES ('data'));");
}
/*
* Called every time you open a database
*/
#Override
public void onOpen(SQLiteDatabase db) {
}
/*
* Called ONCE if DATABASE_VERSION has changed since the last instantiation of DBHelper
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

Related

Android : Change SQLite DB on upgrade

I want to add a column to my existing database
However I'm imagining I'm in the scenario where people have already got a version of the code and database and I'm going to make the changes through a update on google play, therefore previous data cannot be lost
To create my database I used the following code;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
db = openOrCreateDatabase("EJuiceData", Context.MODE_PRIVATE, null);
db.execSQL("create table if not exists Inventory(_id integer primary key autoincrement, NAME TEXT NOT NULL, AMOUNT TEXT, PRICE TEXT, AMOUNTLEFT TEXT, WEIGHT TEXT);");
....
I've looked around online and people are mentioning using the following command to update;
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE Recipe ADD COLUMN NOTES TEXT");
}
}
However onUpgrade is commented out stating the it isn't being called, also no where in my code have I stated what version of the database it is or given a new version
Anyone know how I get around this issue?
Thanks
EDIT;
From looking at the answers I've decided to try do this the most efficient way and what's seen as the best practice
So I've created a new Java Class called MyDBHelper which has the following
package com.sjhdevelopment.shaunharrison.myejuiceapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "EJuiceData.db";
public static final int DATABASE_VERSION = 1;
public MovieDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table if not exists Recipe");
.....
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
database.execSQL("ALTER TABLE Recipe ADD COLUMN NOTES TEXT");
onCreate(database);
}
}
So far I have an error on MovieDatabaseHelper stating 'invalid method declared; return type required
Are you using SQLiteOpenHelper ? If yes you must have a version you send to the super class from the constructor (see documentation)
Here is a code sample. The onUpgrade function will be called when the DATABASE_VERSION changes.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "EJuiceData.db";
public DatabaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table if not exists Inventory(_id integer primary key autoincrement, NAME TEXT NOT NULL, AMOUNT TEXT, PRICE TEXT, AMOUNTLEFT TEXT, WEIGHT TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE Recipe ADD COLUMN NOTES TEXT");
onCreate(database);
}
}
}
EDIT
now you can get access your database using
DatabaseHelper helper = new DatabaseHelper(getContext());
helper.getReadableDatabase().query(...);
//or
helper.getWritableDatabase().insert(...);
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < newVersion)
db.execSQL("DROP TABLE IF EXISTS '" + TABLE_NAME + "'");
onCreate(db);
}
}
You can extend SQLiteOpenHelper like below code, and new your helper class with version param which db version you want to open.
If you open db with version 1, and next time you open db with version 2, the onUpgrade method will be called with param ordVersion = 1 and newVersion = 2, then you can do something to upgrade your db schema here.
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mydata.db";
public static final int VERSION = 1;
private static SQLiteDatabase database;
public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
public static SQLiteDatabase getDatabase(Context context) {
if (database == null || !database.isOpen()) {
database = new MyDBHelper(context, DATABASE_NAME,
null, VERSION).getWritableDatabase();
}
return database;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}

Android/SQLite right way to open/close db?

Im a bit new to OOP so i want to know if im doing things correctly. For communication with database i have created a class SQLiteHelper witch does all the usual stuff (onCreate, onUpdate) and also opens and closes connection.
Here is the class, at the moment it has just on table but more will be added:
public class SQLiteHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "notebook";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_LIST = "list";
public static final String TABLE_LIST_ID = "_id";
public static final String TABLE_LIST_NAME = "name";
public SQLiteDatabase db;
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table " + TABLE_LIST + "(" + TABLE_LIST_ID
+ " integer primary key autoincrement, " + TABLE_LIST_NAME
+ " text not null);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);
onCreate(db);
}
public void open(){
db = getWritableDatabase();
}
public void close(){
db.close();
}
}
And next for each table i will create a new class witch extends previous class andd where i do all the operations relevant to that specific table.
For example ListSQL:
public class ListSQL extends SQLiteHelper {
public ListSQL(Context context) {
super(context);
}
public void delete(int id) {
open();
db.delete(TABLE_LIST, TABLE_LIST_ID + " = " + id, null);
close();
}
}
My question is that in OOP is this the correct way of doing things? Espesially the usage of open/close methods and db and TABLE variables in ListSQL seem kind of strange to me?
I always open the db connection in onResume() and close it in onPause(). In this way database is always open for each activity.
The reason I am not doing it in onCreate() and onDestroy() is once user go to other activity onCreate() of new activity will be called first then onDestroy() of old activity so if I perform any operation(ex:- search in my list or changing the status of user etc) on places other then onCreate() it will crash the app with reason database already closed.
Note: You have to open and close the connection, even if you are using SQLiteHelper class.
According to the Android manual, you do not need to close a database when using an SQLiteOpenHelper. The system will do it for you.
As #Dan mentioned above, you do no need to open and close the database every time you do a read/write operation if you are using SQLiteOpenHelper. The best way to use the database is :
1.
Declare and initialize an instance of SQLiteHelper in your Application base class like this :
public class App extends Application {
public static SQLiteHelper db;
#Override
public void onCreate() {
super.onCreate();
db = new SQLiteHelper(getApplicationContext());
db.open();
}
}
2.
In you activity, or any other place you want to use the DB, initialize the SQLiteHelper object like this :
SQLiteHelper db = App.db;
And then you can use the database anyway you want without having to worry about opening and closing it (:

alter table code in android...

following is the code that i used to alter my table but my app is crashing.
I have create this dbupdateadapter class separately. the records are being added, but the column is not added to the same table
public class dbupdateadapter {
public static final String TABLE_MEMBERID="memberid";
private static final String DATABASE_NAME="myfemmefab.db";
private static final String TABLE_NAME="registeration";
private static final int DATABASE_VERSION=2;
private static final String DATABASE_UPDATE="ALTER TABLE registeration ADD COLUMN(memberid TEXT);";
private static Context context1;
private dbhelper1 helper1;
private SQLiteDatabase sdb1;
public dbupdateadapter(Context con){
this.context1=con;
helper1=new dbhelper1(context1);
}
public class dbhelper1 extends SQLiteOpenHelper{
public dbhelper1(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sdb1){
sdb1.execSQL(DATABASE_UPDATE);
}
#Override
public void onUpgrade(SQLiteDatabase sdb1,int oldver,int newver){
//android.util.Log.w("constants", "upgrading database will destroy the old data");
if(newver>oldver){
sdb1.execSQL(DATABASE_UPDATE);
}
//onCreate(sdb1);
}
}
public dbupdateadapter open() throws SQLException{
sdb1=helper1.getWritableDatabase();
return this;
}
void insertcoldata (String memberid){
ContentValues cv1=new ContentValues();
cv1.put(TABLE_MEMBERID, memberid);
sdb1.insert(TABLE_NAME, null, cv1);
}
public void close(){
helper1.close();
}
}
You should know that in
public void onCreate(SQLiteDatabase db ){ ... }
you should create your tables and populate them with some initial values and you didn't create table in your snippet of code.
for upgrating your tables you should use
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { ... }
Exactly from docs:
Called when the database needs to be upgraded. The implementation
should use this method to drop tables, add tables, or do anything else
it needs to upgrade to the new schema version.
Also have look at
SQL As Understood By
SQLite
Example of how to implement ALTER
TABLE
Use "ALTER TABLE registeration ADD memberid TEXT;"; or "ALTER TABLE registeration ADD COLUMN memberid TEXT;"; You have an error in syntax.
Where are you creating yout table? You are executing DATABASE_UPDATE in your onCreate().

SQLiteOpenHelper not calling onCreate

This is the fist time I've used SQLiteOpenHelper (or databases on android). When I get a writeable database I was wondering why onCreate isnt being called on each new instance of the class. Am I doing something wrong?
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyDatabase.db";
private static final int DATABASE_VERSION = 1;
private String PrSQLcmd = "";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE IF NOT EXISTS Contact(Firstname TEXT, LastName TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
In SQLiteOpenHelper, the meaning of 'onCreate' is different from what it is in an Activity. Here,'onCreate' is called only once, which is the first time you create the database. The next time you run the app, the database is already there, so it won't call 'onCreate'. Your object level initialization should be done in the constructor and not in 'onCreate'
To see 'onCreate' being called, either manually delete the db file, or simply uninstall the app.

Android SQLite and Method for it

How to declare database in android? How we make a database in android and method?
Basically you extend a class with SQLiteOpenHelper and implement onCreate and onUpgrade.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "db_table";
public DatabaseHelper2(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE coordinate (field1 CHAR NOT NULL ,field2 INTEGER NOT NULL ,field3 INTEGER NOT NULL);");
db.execSQL("INSERT INTO spotit VALUES( test ,10,10);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
Then initiate the class in your main activity.
DatabaseHelper db = new DatabaseHelper(this);
db.getReadableDatabase();
db.close();
onCreate will be invoked when you call db.getReadableDatabase()
all you need is here:
http://developer.android.com/guide/topics/data/data-storage.html#db

Categories

Resources