Skip to main content

#2: SQLite database


SQLite

What is SQLite?
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. In addition it requires only little memory at runtime (approx. 250 KByte).


SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java) andREAL (similar to double in Java). All other types must be converted into one of these fields before saving them in the database. SQLite itself does not validate if the types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.



SQLite in Android?
SQLite is available on every Android device. Using an SQLite database in Android does not require any database setup or administration.
You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.
Access to an SQLite database involves accessing the filesystem. This can be slow. Therefore it is recommended to perform database operations asynchronously, for example inside the AsyncTaskclass.
If your application creates a database, this database is by default saved in the directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which the Environment.getDataDirectory() method returns. APP_NAME is your application name.FILENAME is the name you specify in your application code for the database.


SQLiteOpenHelper:
To create and upgrade a database in your Android application you usually subclassSQLiteOpenHelper. In the constructor of your subclass you call the super() method ofSQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the onCreate() and onUpgrade() methods.
onCreate() is called by the framework, if the database does not exists.
onUpgrade() is called, if the database version is increased in your application code. This method allows you to update the database schema.
Both methods receive an SQLiteDatabase object as parameter which represents the database.
SQLiteOpenHelper provides the      methods getReadableDatabase() andgetWriteableDatabase() to get access to an SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this standard.
It is best practice to create a separate class per table. This class defines static onCreate() andonUpgrade() methods. These methods are called in the corresponding methods ofSQLiteOpenHelper. This way your implementation of SQLiteOpenHelper will stay readable, even if you have several tables.

SQLiteDatabase?

SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
More specifically SQLite provides the insert(), update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL statement directly.
The object ContentValues allows to define key/values. The "key" represents the table column identifier and the "value" represents the content for the table record in this column. ContentValuescan be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via theSQLiteQueryBuilder class .
rawQuery() directly accepts an SQL select statement as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.

Cursor:
A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.


To get the number of elements of the resulting query use the getCount() method.



To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
A Cursor needs to be closed with the close() method call.
We need to write our own class to handle all database CRUD(Create, Read, Update and Delete) operations.

Example:
Step1: Create a new class called StudentDB.java

Step2: Now extend y StudentDB.java class from SQLiteOpenHelper.

Step3: After extending your class from SQLiteOpenHelper you need to override two methodsonCreate() and onUpgrage()


onCreate() – These is where we need to write create table statements. This is called when database is created.


onUpgrade() – This method is called when database is upgraded like modifying the table structure, adding constraints to database etc.,

Comments

Popular posts from this blog

#3: Collapsing Toolbar

Collapsing Toolbar         CollapsingToolbarLayout is a ViewGroup that provides many of the visual characteristics and interactions for collapsing toolbars specified in the material guidelines. To create the collapsing toolbar, CollapsingToolbarLayout integrates with AppBarLayout, CoordinatorLayout, Toolbar, and a scrollable content view, such as RecyclerView. How to work with Collapsing Toolbar:     To add a collapsing toolbar to your layout, place the CollapsingToolbarLayout inside an AppBarLayout. Then, add a Toolbar and any other views as a child to the CollapsingToolbarLayout. Make sure that the entire view structure is inside a CoordinatorLayout to take advantage of CollapsingToolbarLayout’s scrolling and features. Sample Code: <android.support.design.widget.CoordinatorLayout     android:layout_width="match_parent"     android:layout_height="match_parent">     <!-- Scrollable view here -->   <com.google.android.mat

Activity Life Cycle States

      Activity Life Cycle Example  https://drive.google.com/file/d/1ald91YAfWEit05irie7NolPm4h1OFpIy/view?usp=sharing Activity Life Cycle         As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle. The Activity class provides a number of callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides.       Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot. In other words, each callback allows you