SQLiteOpenHelper:NullPointerException

时间:2014-03-23 22:57:13

标签: android sqlite android-asynctask sqliteopenhelper

我正在尝试将数据保存到SQLite数据库。

AddBook.java

    public class AddBook extends Activity {
        String myUrl = "";
        DownloadBook obj_Downloadbook;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            obj_Downloadbook = new DownloadBook(AddBook.this);//line26
    ...
    obj_Downloadbook.execute(myUrl);

此活动正在调用 DownloadBook.java 类,该类扩展了AsyncTask。在DownloadBook.java类中,我正在检索html作为字符串并保存到文件。保存后,我正在尝试将标题和作者记录到数据库中

public class DownloadBook extends AsyncTask<String, Void, String> {
private Context context;
public DownloadBook(Context context) {
    this.context = context;
}
MyDatabase myDatabase=new MyDatabase(context);//line27
...
myDatabase.addBookInformation(title, author);

为了管理SQLite数据库,我是using android-sqlite-asset-helper库。在库的github中,它写成:SQLiteAssetHelper旨在作为框架的SQLiteOpenHelper的替代品。的 MyDatabase.java

public class MyDatabase extends SQLiteAssetHelper {
   MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);//line21
        setForcedUpgradeVersion(3);
    }
   ...
   public void addBookInformation(String title, String author){
   ...

这会产生以下错误:

03-24 03:13:37.248: E/AndroidRuntime(21237): Caused by:
java.lang.NullPointerException 03-24 03:13:37.248:
E/AndroidRuntime(21237):    at
com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:110)
03-24 03:13:37.248: E/AndroidRuntime(21237):    at
com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:130)
03-24 03:13:37.248: E/AndroidRuntime(21237):    at
com.joericharduz.akita.MyDatabase.<init>(MyDatabase.java:21) 03-24
03:13:37.248: E/AndroidRuntime(21237):  at
com.joericharduz.akita.DownloadBook.<init>(DownloadBook.java:27) 03-24
03:13:37.248: E/AndroidRuntime(21237):  at
com.joericharduz.akita.AddBook.onCreate(AddBook.java:26)

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

在构造函数运行之前初始化成员变量。所以在这里,

public class DownloadBook extends AsyncTask<String, Void, String> {
    private Context context;
    public DownloadBook(Context context) {
        this.context = context;
    }
    MyDatabase myDatabase=new MyDatabase(context);//line27
在构造函数中初始化myDatabase之前,

... null初始化为context context

new MyDatabase(context) initiazlization移动到构造函数。