Sqliteopenhelper Failing to Call Oncreate

SQLiteOpenHelper failing to call onCreate?

The onCreate is not a constructor for the database class. It is only called if you try to open a database that does not exist.
To open/create the database you need to add a call to one of these methods:

public class SmartApp extends Activity implements OnSharedPreferenceChangeListener {
private SmartDBHelper dBHelper;
public void onCreate(Bundle savedInstanceState) {
//where i am wanting to create the database and tables
dBHelper = new SmartDBHelper(getContext());
// open to read and write
dBHelper.getWritableDatabase();
// or to read only
// dBHelper.getReadableDatabase();
}
}

It is a bit big but here is my DatabaseAdapter you can take a look at: http://saintfeintcity.org/projects/sfc/repository/entry/trunk/src/org/saintfeintcity/database/GameDbAdapter.java

Android SQLiteOpenHelper: Why onCreate() method is not called?

I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable

SQLiteDatabase db;

In the SQLiteOpenHelper subclass and calling

 db = getWritableDatabase();

in the constructor.

The answer to this question also includes helpful information: SQLiteOpenHelper failing to call onCreate?

I hope this helps!

onCreate method doesn't get called in DatabaseHandler extends SQLiteOpenHelper

Well, the real reason why onCreate() method wasn't working for me because it is called only the first time the app runs. Or when you change the DATABASE_VERSION then onUpgrade gets called which in turn calls the onCreate method again.

I believe this is the default android working.

P.S I could get the onCreate working everytime by either changing the database version or deleting the database file from /data/data/packagename/databases/

SQLiteOpenHelper: onCreate() method not called on physical device

Let i try to explain you some things.

In an application to connect to the database , we specify the name and version of the database . In this situation, the following may occur :

1) There is no database . This may be for example in the case of initial setting program. In this case, the application itself must create the database and all the tables in it. And further, it is already working with the newly created database.

2) Database exists, but its version is outdated. It may be the case update. For example a new version of the program need additional fields in the old tables or new tables . In this case, the application must update existing tables and create new ones if necessary.

3) There is a database and its actual version . In this case, the application successfully connects to the database and running.

As you know , the phrase " application must " tantamount to the phrase " the developer must ", ie it is our task . To handle the situations described above , we need to create a class that inherits for SQLiteOpenHelper. Call it DBHelper. This class will provide us with methods to create or update the database in case of their absence or obsolescence.

onCreate - a method that will be called if the database to which we want to connect - does not exist(it's your case)

Android SQLite, onCreate() not being called

I'd suggest using the following (temporarily) in the activity :-

DatabaseHelper myDBHelper = new DatabaseHelper(this); //<<<<<<<<< you appear to already have the equivalent of this line (if so use whatever variable name you have given to the DatabaseHelper object)

Cursor csr = myDBHelper.getWritableDatabase().query("sqlite_master",null,null,null,null,null,null);
DatabaseUtils.dumpCursor(csr);
csr.close();

Run and then check the log. You should see output for your modules_table and also sqlite_sequence (the latter because you have coded autoincrement.

sqlite_master is a system table that stores system information, such as table and index names i.e. the schema.

Additional - access to the database file

On a device that isn't rooted each applications data (data/data) is protected so you won't be able to see the database file.

On an emulator, it depends upon the emulator. I believe later versions of Android studio do now allow access e.g. :-

Sample Image

  • Note the above is Android 10.1 Pie (API 28) and hence the database has Write-Ahead Logging (WAL) and thus the -shm and -wal files also exist.

  • The package is mjt.pvcheck. The full path is data/data/mjt.pvcheck/databases.

    • As you can see cache directory, then I'd suggest that for some reason, perhaps a failure, the database doesn't exist, but you do appear to have access as per however upon checking through the virtual device file explorer the only sub folder I have within my package is the cache.
    • Perhaps, try rerunning on the device (note in device explorer re-select the device as it doesn't refresh), which may be another reason why you didn't see the database.

onCreate() method of SQLiteHelper is never called

This may help with future development

MySQLiteHelper - Defines Database, tables etc.

public class MySQLiteHelper extends SQLiteOpenHelper {

private static final String FILE_NAME = "application.db";
private static final int DB_VERSION = 1;
private final String TAG = MySQLiteHelper.class.getCanonicalName();
private static SQLiteDatabase database = null;

public MySQLiteHelper(Context context) {
super(context, FILE_NAME, null, DB_VERSION);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//version 1
database.execSQL(ProductsTbl.CREATE_SQL);
//can create new tables if necessary, make sure to increase database version

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.i(TAG, "Upgrading from version " + oldVersion + " to version "
+ newVersion);
for (int i = oldVersion + 1; i <= newVersion; i++) {
Log.i(TAG, "version is becoming current " + i);
switch (i) {
case 2:
db.execSQL(ProductsTbl.CREATE_SQL);
break;
//add more cases for each additional table added

}
}
}

public static class ProductsTbl {
public static final String TABLE_NAME = "products";
public static final String ID = "_id";
public static final String URL = "url";
public static final String TITLE = "title";
public static final String PRICE = "price";
public static final String[] TABLE_COLUMNS = { ID, URL, TITLE, PRICE };
public static final String CREATE_SQL = "create table " + TABLE_NAME
+ "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ URL + " TEXT,"
+ TITLE + " TEXT,"
+ PRICE + " INTEGER);";
}

}

MySQLiteDatasource - Defines access methods, Insert, Delete, etc.

public class MySQLiteDatasource {

//Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;

public MySQLiteDatasource(Context context) {
dbHelper = new MySQLiteHelper(context);
}

public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}

public void close() {
dbHelper.close();
}

public void insertProduct(String url, String title, String price) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.ProductsTbl.URL, url);
values.put(MySQLiteHelper.ProductsTbl.TITLE, title);
values.put(MySQLiteHelper.ProductsTbl.PRICE, price);

try {
database.insertOrThrow(MySQLiteHelper.ProductsTbl.TABLE_NAME, null, values);
} catch (SQLiteConstraintException e) {
//System.out.println(e);
Log.e("SQLite Database", "Unable to INSERT into Database, possible duplicate topic already exists.");
}
}

}

Here is how you could use the 2 classes inside an activity or something similar.

  public static void addProductToDB(String url, String title, String price) {
MySQLiteDatasource datasource = new MySQLiteDatasource(this);
datasource.open();
datasource.insertProduct(url, title, price);
datasource.close();
}

You may also want to look into defining a Product object to hold data that is obtained from the database at a later point.

Android Sqlite - unable to call database handler outside of onCreate

Try using a singleton design pattern to access the data.
Check this post out to see how.

As far as I can see loginSuccess() is called after receiving data from a web server.

It is probable that your app is trying to write data to the database simultaneously.

Edit:
When using multiple instances of DatabaseHandlerV2 consider closing the connection.

Example:

Helper:

public class SampleHelper extends SQLiteOpenHelper {

private static SampleHelper instance;
private static Context mContext;

public static synchronized SampleHelper getHelper(Context context) {
if (instance == null)
instance = new SampleHelper(context);
return instance;
}

private SampleHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
}

Writing:

SampleHelper helper = SampleHelper.getHelper(mContext);
SQLiteDatabase writableDb = helper.getWritableDatabase();
String statement = "INSERT OR REPLACE INTO table_name(colA,colB) VALUES (valA,valB)";
writableDb.execSQL(statement);

Reading:

Cursor cursor = null;
try {
cursor = SampleHelper.getHelper(mContext).getReadableDatabase().rawQuery("SELECT colA FROM table_name");
if (cursor.moveToFirst()) {
do {
/**read the data here**/
} while (cursor.moveToNext());
}
}
finally {
if(null != cursor)
cursor.close();
}

As you can notice the connection to the database is not closed.
When using a singleton pattern we use only one instance of SampleHelper so we can keep the connection opened.

I did not check your updated log untill now. It says:

A SQLiteConnection object for database '/data/data/com.dummies.myapplication/databases/userManager' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

That means your did not close the connection(db.close();), thus the null pointer exception when executing this.getReadableDatabase(); on deleteTableData() method.

I still recommend using the sample code provided to avoid database is locked exceptions.

For openOrCreateDatabase exception check this post. Notice that the database name ends with .db. Also check if your context is null or not.

When the SQLiteOpenHelper onCreate method is called?

The documentation says:

The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.

this.getWritableDatabase() is not calling onCreate()

You're catching the exception in onCreate(SQLiteDatabase db) and silently letting it off. The crash should have been taken place in your onCreate() method itself as your query to create the table is wrong. You're missing commas between various columns in your create query.

private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "+ TABLE_EXPENSES+"(" +
COLUMN_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_AMOUNT+ " TEXT, " +
COLUMN_NOTE+ " TEXT, " +
COLUMN_CATEGORY+ " TEXT, "+
COLUMN_DATE+" TEXT" + ")";

onCreate() is not called by getWritableDatabase()

The creation only happens once (that's the whole sense of an database helper).

Did you check whether your database was created? It's located at /data/data/your.package.name/databases/dbname.

If you clear your application data in the android application settings, your onCreate should be called again...



Related Topics



Leave a reply



Submit