Issue
I am trying to save data to SQLite database.
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);
This activity is calling DownloadBook.java class which extends AsyncTask. In DownloadBook.java class, I am retrieving html as string and saving to file. After saving, I am trying to record title and author into database
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);
In order to manage SQLite database, I am using android-sqlite-asset-helper library. In library's github, it is written that: SQLiteAssetHelper is intended as a drop in alternative for the framework's 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){
...
And this is giving following error:
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)
How to solve this problem?
Solution
Member variables are initialized before the constructor is run. So in here,
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
is initialized with a null
context
before the context
is initialized in the constructor.
Move the new MyDatabase(context)
initiazlization to the constructor.
Answered By - laalto
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.