I tried to create an SQLite database and do some stuff with it. But I found that my onCreate
method is not even invoked!!
I am sending a message to LogCat on the begining of the onCreate
method.
My assumption is, the (super) constructor will invoke onCreate
method. Is that right?
My Code:
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.content.Context; import android.database.Cursor; import android.content.ContentValues; import android.util.Log; public class DatabaseHandler extends SQLiteOpenHelper { // Static Constants /*** Database details ***/ // Database version private static final int DATABASE_VERSION = 1; // Database name private static final String DATABASE_NAME = "database_name"; /*** Database Tables ***/ /** Events **/ // Event table private static final String TABLE_EVENT = "event"; // Event table columns private static final String COLUMN_EVENT_EID = "_eid"; private static final String COLUMN_EVENT_CREATION_DATE = "creation_date"; private static final String COLUMN_EVENT_TITLE = "title"; private static final String COLUMN_EVENT_ICON = "icon"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.e("MyApp", "onCreate invoked"); // Tables creation queries String CREATE_EVENT_TABLE = "create table " + TABLE_EVENT + "(" + COLUMN_EVENT_EID + " integer primary key, " + COLUMN_EVENT_CREATION_DATE + " text, " + COLUMN_EVENT_TITLE + " text, " + COLUMN_EVENT_ICON + " text)"; // Creating tables db.execSQL(CREATE_EVENT_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.e("MyApp", "onUpgrade invoked"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENT); } }
MainActivity Code:
import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DatabaseHandler db = new DatabaseHandler(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
The documentation says:
The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With