Android – SQLite and SQLiteOpenHelper class

SQLite provides a structured data storage and it is lightweight and run-in process, which means the library runs as part of the application. There is no need for server installation and configuration. SQLite has 5 datatypes:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

You can read more here.

SQLiteOpenHelper class

SQLiteOpenHelper class provides methods to access, manage the creation and version management of the database. To create an SQLiteOpenHelper class, create a new Java class file. The class should extend the SQLiteOpenHelper class.

Implement an SQLiteOpenHelper class, <span>Android – SQLite and SQLiteOpenHelper class</span>, KandZ

Press Alt + Enter and select Implement Methods. Click OK

Implement an SQLiteOpenHelper class, <span>Android – SQLite and SQLiteOpenHelper class</span>, KandZ
  • onCreate – is called only if the database does not exist. Here you can create the tables and add any initial data
  • onUpgrade – is called when a new version of the Database is expected. Upgrade the tables if necessary.

Create public fields one for the database filename and one for the version. Now create a constructor with one parameter, Context.

Implement an SQLiteOpenHelper class, <span>Android – SQLite and SQLiteOpenHelper class</span>, KandZ
the third argument is the factory and not needed at the moment that is why is null

I have created the SQL creation string in the contract class. Read this post. Now implement the onCreate method and create the tables using the execsql method.

Implement an SQLiteOpenHelper class, <span>Android – SQLite and SQLiteOpenHelper class</span>, KandZ

Just remember:

  • Create a GameDBhelper field
private GameDBHelper dbHelper;
  • it is common to instantiate the implemented SQLiteOpenHelper class inside one Activity’s onCreate hook method
dbHelper = new GameDBHelper(this);
  • remember to close the database inside one Activity’s onDestroy hook method.
dbHelper.close();
  • The database is not yet created until you try to access it, for example with getReadableDatabase or getWritableDatabase methods.
SQLDatabase db = dbHelper.getReadableDatabase();

THE END!!!

98340cookie-checkAndroid – SQLite and SQLiteOpenHelper classAndroid – SQLite and SQLiteOpenHelper class

Related posts

5 Thoughts to “Android – SQLite and SQLiteOpenHelper class

  1. […] Android – SQLite and SQLiteOpenHelper class […]

  2. […] You can read about SQLiteOpenHelper here. […]

  3. […] Provide must connect to the SQLite Database, using an SQLiteOpenHelper class. Read more here how to implement this class. Create a member […]

  4. […] use SQLiteHelper class, read this post, in the following examples. Query needs at least the two following arguments, table and […]

  5. […] Provide must connect to the SQLite Database, using an SQLiteOpenHelper class. Read more here how to implement this class. Create a member […]

Comments are closed.