2010-10-08 163 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