2016-11-08 27 views
0

我在內存中創建一個數據庫的數據庫如下我從內容提供商光標:如何使用在內存中創建

@Override 
    public Cursor query(Uri uri, String[] projection, String selection, 
         String[] selectionArgs, String sortOrder) { 
     final SQLiteDatabase db = myDb.getReadableDatabase(); 
     Cursor retCursor; 
     switch (sUriMatcher.match(uri)) { 
      case LABEL: 
       retCursor = db.query(
         IOContract.IoEntry.TABLE_NAME, 
         projection, 
         selection, 
         selectionArgs, 
         null, 
         null, 
         sortOrder 
       ); 
       break; 

      default: 
       throw new UnsupportedOperationException("Unknown uri: " + uri); 
     } 

在我的活動光標:

Cursor c = contentResolver.query(cpUri, null, selection, argms, null); 

當我使用DATABASE_NAME創建數據庫時,數據庫在磁盤上創建,並且返回光標。

 public DbIoDatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
//  super(context, null, null, DATABASE_VERSION); 
     this.myContext = context.getApplicationContext(); 
    } 

當我使用空在內存中創建它,我得到光標沒有元素 - 儘管返回的指針不爲空。

public DbIoDatabaseHelper(Context context) { 
//  super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     super(context, null, null, DATABASE_VERSION); 
     this.myContext = context.getApplicationContext(); 
    } 

有沒有一種方法,我可以得到一個有效的光標在內存中創建數據庫時,我該怎麼辦呢? 任何幫助將不勝感激。謝謝。

+0

您是否已將數據添加到數據庫?當你的數據庫只在內存中時,它不會在你的應用程序運行之間保存數據,這意味着在添加數據之前的任何查詢都將是空的。 – XGouchet

回答

0

謝謝XGouchet爲您的答案。我通過以下方式解決了我的問題:我讀過在內存中創建的數據庫僅對創建它的活動可見。因此,我在OnCreate()方法的Content Provider中創建了數據庫。

@Override 
    public boolean onCreate() { 
     myDbData = new DatabaseData(); 
     myDb = new IODatabaseHelper(getContext()); 
     initializeDb(); // method that populates the database 
     if (myDb == null) { 
      ret = false; 
     } 
     return true; 
    } 
相關問題