2010-10-08 165 views
0

我想獲取創建數據庫的內容提供者的代碼。我使用的工具位於這裏tools/sqllite3.exe來檢查數據庫是否被創建。Android內容提供商

請讓我知道這件事情的一步一步的過程...

感謝, -D

回答

3

你不箱與ContentProvider的數據庫,但與SQLiteOpenHelper類。至少,這是做

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(); 
     } 
    } 
} 

的更好的方式來簡單地

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

實例化你的助手,那麼助手將創建數據庫時,如果它不存在,如果舊版本升級存在,或者如果它存在,只要打開它,版本匹配

+0

謝謝...這工作! – 2010-10-09 18:30:21

1

我用這個教程

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

我現在有一個很好的內容提供程序,可以讓我輕鬆查詢表格,並且比其他數據庫更靈活。

+0

這也適用,但很多描述... – 2010-10-09 18:30:58

+0

關於我發佈的教程,我不喜歡或必須做的唯一的事情就是使用完全限定的內容URI,因爲我在同一個應用中使用它。我只是使用BooksProvider.TITLE或BooksProvider._ID,它使生活更加簡單。但根據教程在外部軟件包中使用它,您需要使用諸如「content://net.learn2develop.provider.Books/books」之類的內容。 – Opy 2010-10-12 14:23:30