5

I have Android service, that uses SQLite database. I faced some troubles with database initialization.

I have class DBHelper:

public class DBHelper extends SQLiteOpenHelper{
public boolean db_loaded=false;
public DBHelper() {
    super(ContextBean.getLocalContext(), "resplugin1.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table tasks ("
            + "id integer primary key autoincrement,"
            + "title text);");
    db_loaded=true;
}

I have client class that uses it:

public class DataProvider {
private SQLiteDatabase database;
private DBHelper dbHelper;

public DataProvider(){
    dbHelper=new DBHelper();
    database = dbHelper.getWritableDatabase();
}
public void close(){
    dbHelper.close();
}
public TaskDescriptor getTaskById(int id){
    while(dbHelper.db_loaded==false){}
    String[] args={Integer.toString(id)};
    if(database==null){
        Log.d("ResPluginService1","DATABASE IS NULL");
    }
/*...*/
}

The problem is that database object is always NULL. getWritableDatabase method throws no exceptions, it just returns null. What can cause so strange behaviour?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Lecko
  • 1,275
  • 1
  • 17
  • 32
  • The `db_loaded` flag and busy-waiting on it is completely wrong. `getWritableDatabase()` always returns a database or throws an exception. Have you overridden the method yourself? – laalto May 06 '14 at 07:50
  • put your execSQL inside a try catch and do some log ? – An-droid May 06 '14 at 08:12
  • 1. I have not overriden getWritableDatabase myself 2.I have put both getWritableDatabase and execSQL in `try-catch` but I got nothing, Also I mentioned that database is created, after executing this command I can see in app properties that some data appears – Lecko May 07 '14 at 05:40
  • 1
    DId you find a solution for this? I am having the same problem. When I surround the call to `getWritableDatabase()` with try/catch, it shows an NPE – Al Lelopath Apr 16 '15 at 16:06

0 Answers0