Binoy Babu
Binoy Babu

Reputation: 17139

Error on opening database SQLite

I'm using the following method to open my SQLite db.

private void open() {
    database = dbHelper.getReadableDatabase();
}

He's the relevent parts of dbHelper.

public void onCreate(SQLiteDatabase la_db) {
    String s;
    try {
        InputStream in = context.getResources().openRawResource(R.raw.sql);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder.parse(in, null);
        NodeList statements = doc.getElementsByTagName("statement");
        for (int i = 0; i < statements.getLength(); i++) {
            s = statements.item(i).getChildNodes().item(0).getNodeValue();
            la_db.execSQL(s);
        }
    } catch (Throwable t) {
        Toast.makeText(context, t.toString(), 50000).show();
    }
}

Part of sql.xml

....
<statement>
CREATE TABLE IF NOT EXISTS la_table (
    _id INTEGER PRIMARY KEY AUTOINCREMENT, 
    suggest_text_1 VARCHAR(100),
    test_value_1 VARCHAR(100),
    test_value_2 VARCHAR(100),
    test_type_1 VARCHAR(50),
    suggest_intent_data VARCHAR(5))
</statement>
<statement>INSERT INTO la_table VALUES(1,"Sodium (Na)","310 - 330 mg/dl",null,"Serum","1")</statement>
<statement>INSERT INTO la_table VALUES(2,"Potassium (K)","14 - 20 mg/dl","3.5 - 5 mmol/L or mEq/L","Serum","2")</statement>
.....

And I'm getting this error :

01-01 00:59:38.725: E/AndroidRuntime(2060): Caused by: java.lang.NullPointerException
01-01 00:59:38.725: E/AndroidRuntime(2060):     at com.assistant.lab.royale.DataSource.open(DataSource.java:42)
01-01 00:59:38.725: E/AndroidRuntime(2060):     at com.assistant.lab.royale.DataSource.listViewCursor(DataSource.java:25)
01-01 00:59:38.725: E/AndroidRuntime(2060):     at com.assistant.lab.royale.LabAssistant.onCreate(LabAssistant.java:24)
01-01 00:59:38.725: E/AndroidRuntime(2060):     at android.app.Activity.performCreate(Activity.java:4465)

Upvotes: 0

Views: 184

Answers (2)

Boris Strandjev
Boris Strandjev

Reputation: 46963

The code you provided will most definitely fail. You need to provide a context in the constructor of dbHelper. I suggest you change your class like that:

Add a constructor:

private DatabaseHelper dbHelper;
public DataSource(Context context) {
    this.dbHelper =  new DatabaseHelper(context);
}

You can not avoid passing in the context, but this usually is not a big problem, from every Activity you can just pass in this as the context. After this change you should be able to use your dbHelper without any problems.

Upvotes: 1

zapl
zapl

Reputation: 63955

dbHelper is null in your open(), you need to create an instance if your helper before you can use it.

Upvotes: 1

Related Questions