Banal creation of SQLite Android database

public class DatabaseHelper extends SQLiteOpenHelper { private Context context; public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context,name,factory,version); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { Toast.makeText(context, "onCreate", Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } 

I call in MainActivity by clicking on the button

 public void onInsert(View view) { DatabaseHelper databaseHelper = new DatabaseHelper(this,"mydb.db",null,1); } 

The OnCreate method is not even called, the database is not created. Checked on the emulator with Androyd 6.0.0 and on Nexus 5 with Androyd 6.0.1 - results 0, no errors are displayed.

  • one
    Version tried to change? The base has already been created ... - Yura Ivanov
  • The onCreate () method is executed only if the database has not been previously created (a database with this name does not exist), otherwise the onUpgrade () method is executed and then only if the database version number is increased. - pavlofff

1 answer 1

In the MainActivity execute:

 public void onInsert(View view) { DatabaseHelper databaseHelper = new DatabaseHelper(this, "mydb.db", null, 1); SQLiteDatabase db = databaseHelper.getWritableDatabase(); } 

Then, if the database does not exist, it will work onCreate , create a database and return it for work, if it exists, it will simply return it without calling the method.