首页 > 代码库 > NullPointerException when calling getReadableDatabase()

NullPointerException when calling getReadableDatabase()

故事的背景,甲午年末,某大型项目突遇新需求,数据库需由Mysql转到SQLite,于是百万大军浩浩汤汤的代码搬迁开始了,途中几经突围,终于杀出一片天,前方传来捷报,哈哈~~


这个问题困扰了好几天,在stackoverflow上搜了很多帖子,都没能解决,比如:

getReadableDatabase() Null Pointer Exception

NullPointerException 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的关闭方法0
public 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()