2016-09-17 86 views
0

簡單地說,這是我的課getWritableDatabase()從來沒有被稱爲

public class sqlite extends SQLiteOpenHelper{ 
    public SQLiteDatabase db; 
    public sqlite(Context context , String db_name , int db_version){ 
    super(context, db_name, null, db_version, null); 
    try{this.db=getWritableDatabase();}catch(Exception e){this.db=getReadableDatabase();} 
    } 

當我打電話新sqlite(*****);功能getWritableDatabase()getReadableDatabase()總是導致錯誤(NullPointerException異常的空對象引用),所以什麼是正確的引用我必須打電話來成功執行這些功能?

編輯我發現了一個解決方案,但仍IAM爲什麼wounder上面的代碼不能正常工作? 的解決方案是從源碼除去getWritableDatabase()(擴展SQLiteOpenHelper)構造函數的操作方法它的自我,即:直接之前的CRUD方法, 我不知道失敗的原因,如果從構造稱爲

+0

你在哪裏使用'db'變量?我認爲最好首先實例化你的'sqlite'(爲什麼是一個類的小寫名字?)對象,然後使用它的引用來獲得WritableDatabase。 – ishmaelMakitla

+0

@Sherif Eldeeb爲什麼你想要它在構造函數中調用?從你從哪裏獲取數據庫表,從資產或代碼?以便我可以爲您提供相同的解決方案。 – Nisarg

+0

@Nisarg來自SyncAdaptor類 –

回答

1

您需要從構造函數中刪除對​​的調用。相反,只要你想使用數據庫幫助程序,你可以簡單地調用你的sqlite類的實例(我強烈建議你重命名爲有意義的東西 - 遵循Java類的適當命名約定)。

//Here is an example (using this from an Activity or some other class): 
//pass appropriate values for the arguments... 
sqlite myDatabaseHelper = new sqlite(context, db_name, db_version); 
//here you can get the writable-database object 
SQLiteDatabase sqlDB = myDatabaseHelper.getWritableDatabase(); 
//from here you can perform your database operations - like querying/inserting values, etc 
+0

我想要在構造函數內或類sqlite本身中調用getWritableDatabase(),即用戶不必自己調用此函數 在構造函數中調用getWritableDatabase()會出現什麼問題 –