SQLiteOpenHelper: NullPointerException



我正在尝试将数据保存到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数据库,我使用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)

如何解决这个问题?

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

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

…在构造器初始化context之前,先用null context初始化myDatabase

移动new MyDatabase(context)初始化到构造函数

相关内容

  • 没有找到相关文章

最新更新