views:

34

answers:

2

Hi,

I want to get a code of content provider which a database is created. I am using the tool which located here tools/sqllite3.exe to check if the database is created.

Please let me know the step by step procedure for this thing ...

Thanks, -D

+2  A: 

You don't crate the database with the ContentProvider, but with the SQLiteOpenHelper class. At least that's the better way of doing it

class MyDatabase extends SQLiteOpenHelper {
    public MyDatabase(Context context, dbName, null, version){
        super(context, dbName, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String createItemsTable = "create table mytable ("+
            "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "_title TEXT NOT NULL, " +
            "_subtitle TEXT NULL " +
        " );";

        // Begin Transaction
        db.beginTransaction();
        try{
            // Create Items table
            db.execSQL(createItemsTable);

            // Transaction was successful
            db.setTransactionSuccessful();
        } catch(SQLException ex){
            Log.e(this.getClass().getName(), ex.getMessage(), ex);
        } finally {
            // End transaction
            db.endTransaction();
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String dropItemsTable = "DROP TABLE IF EXISTS mytable";

        // Begin transaction
        db.beginTransaction();

        try {
            if(oldVersion<2){
                // Do your update/alter code here
            }

            db.setTransactionSuccessful();
        } catch(Exception ex){
            Log.e(this.getClass().getName(), ex.getMessage(), ex);
        } finally {
            // Ends transaction
            // If there was an error, the database won't be altered
            db.endTransaction();
        }
    }
}

them simply instantiate your helper with

MyDatabase myDb = new MyDatabase(getContext(),"databasename.db", null, 1); 

The helper will then create the database, if it doesn't exist, upgrade it if an older version exists or simply open it if it exists and the version matches

Tseng
Thanks ... this worked!
Dee Jay'
+1  A: 

I used this tutorial

http://www.devx.com/wireless/Article/41133/1763/page/2

I now have a nice content provider that allows me to easily query the table and is much more flexible than the other databases out there.

Opy
This also works, but a lot of description ...
Dee Jay'
The only thing about the tutorial I posted that I didnt like or have to do was use the fully-qualified content URI since I was using it in the same app. I just use BooksProvider.TITLE or BooksProvider._ID and it makes life alot more simple. But according to the tutorial to use it in external packages you need to use something like "content://net.learn2develop.provider.Books/books".
Opy