NullPointerException when calling getReadableDatabase()

來源:互聯網
上載者:User

標籤:android開發   stackoverflow   mysql   sqlite   經驗   

故事的背景,甲午年末,某大型項目突遇新需求,資料庫需由Mysql轉到SQLite,於是百萬大軍浩浩湯湯的代碼搬遷開始了,途中幾經突圍,終於殺出一片天,前方傳來捷報,哈哈~~


這個問題困擾了好幾天,在stackoverflow上搜了很多文章,都沒能解決,比如:

getReadableDatabase() Null Pointer ExceptionNullPointerException on getReadableDatabase()SQLite Android cannot open database file等。
最後還是參考一個例子,加上我這幾天在sqlite的編碼經驗,終於解決了這個問題。
1.首先是DbHelper類(extends SQLiteOpenHelper)的建構函式:public DbHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);// TODO Auto-generated constructor stub}onCreate()等三個方法就不細說了。2.寫一個sqlite的操作類
private DbHelper dbHelper;private SQLiteDatabase db;//建構函式,很關鍵,就是new了一個DbHelper對象,初始化SQLiteDatabase        //在Android開發中Context很重要,往往是普通類和Activity等Android平台類的橋樑。public DbOperations(Context context){dbHelper = new DbHelper(context);}//封裝sqlite的開啟方法public void open() throws SQLException{db = dbHelper.getReadableDatabase();}//封裝sqlite的關閉方法0public void close(){dbHelper.close();}
舉例使用://擷取使用者的觀看記錄public List getViewRecord(User user){List list = new ArrayList();String sql = "select * from showlist where showId in(select  showId from  viewrecord where userId=?)";// myDbHelper = new DbHelper(LoginActivity.this,DbHelper.DATABASE_NAME,null,DbHelper.DATABASE_VERSION);// db = myDbHelper.getReadableDatabase(); this.open();Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(user.getUserId())});while(cursor.moveToNext()){//String showName = rs.getString("showName");list.add(new Show(cursor.getInt(0),cursor.getString(1),cursor.getString(2)) );Log.i("sql-getViewRecord",cursor.getInt(0) + cursor.getString(1) + cursor.getString(2));// System.out.println("視頻名:" + showName);} cursor.close();this.close();return list;}
然後就可以在需要的地方調用此方法了。

more information refer to :Android SQLite Example(recommendation):http://examples.javacodegeeks.com/android/core/database/sqlite/sqlitedatabase/android-sqlite-example/
Android SQLite Database Tutorial:http://www.tutorialspoint.com/android/android_sqlite_database.htm

NullPointerException when calling getReadableDatabase()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.