Miyerkules, Enero 23, 2013

Android Database Programming basics (SECOND STEP)

 
Second, create a class that extends the SQLiteOpenHelper class
import static android.provider.BaseColumns._ID;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
    String sqlcreate = "CREATE TABLE todo( " + _ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT);";
    public DbHelper(Context ctx) {
        super(ctx,"tododb.db",null, 1);
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sqlcreate);
    }
   
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
        db.execSQL("DROP TABLE IF EXISTS tododb.db");
        onCreate(db);
    }
   
}
You need to do 3 things at a minimum when defining a SQLiteOpenHelper.
Define a public constructor that accepts a Context object. This context is the context of the Activity class where you will instantiate the Helper class. Call the super constructor so that you don't break the chain. The first parameter to super constructor is the context object---you know this already, next parameter is the name of database you want to create; third parameter is a cursor factory, you can ignore this for now, that is why I passed null to it. The last parameter is an integer value which stands for the database version. I placed one (1) because it is my first version of this database. When you revise the schema of the database, increase this value by one so that the onUpgrade() method kicks in---it will perform some sort of an ALTER database command in your behalf.
Override the onCreate() method. This is where you can execute DDL (SQL Data Definition) commands against the database.
Override the onUpgrade() method, even if you won't need it yet. You won't be able to compile unless you override this method

1 komento: