Android Unit V - 10 Mark Questions (JNTUH)
1. Introduction to SQLite Database in Android
SQLite is a lightweight, self-contained, serverless, and transactional SQL database engine
integrated into Android. It provides a robust mechanism for managing local data in Android
apps. Developers use SQLite when an app needs to store structured data locally, like user
profiles, messages, or application settings.
SQLite stores data in tables made of rows and columns. Each row represents a data item,
and each column represents the properties of that item. SQLite supports most SQL syntax
and operations such as SELECT, INSERT, UPDATE, and DELETE.
In Android, SQLite is accessed using the `SQLiteDatabase` class. To create or manage a
database, developers usually extend the `SQLiteOpenHelper` class and override its
`onCreate()` and `onUpgrade()` methods.
Example structure of a database helper class:
```java
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "MyDatabase", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE students(id INTEGER PRIMARY KEY, name TEXT, age
INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS students");
onCreate(db);
}
}
```
SQLite provides an excellent solution for local data storage and is often used in apps that
need data persistence across sessions without relying on a remote server.
2. Opening and Creating a Database
In Android, databases are opened or created using the `SQLiteOpenHelper` class. This class
simplifies the process of creating, opening, and upgrading databases.
When you extend `SQLiteOpenHelper`, you implement two essential methods:
- `onCreate(SQLiteDatabase db)`: called when the database is first created.
- `onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)`: called when the
database version changes.
### Creating a Database
To create a database, instantiate your helper class and call `getWritableDatabase()` or
`getReadableDatabase()`. This automatically triggers `onCreate()` if the database doesn't
exist.
Example:
```java
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase(); // Creates or opens the database
```
### Database Path
By default, Android databases are stored in `/data/data/<package_name>/databases/`.
### SQLiteOpenHelper Example
```java
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "StudentDB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, age
INTEGER);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS students");
onCreate(db);
}
}
```
This approach ensures database creation and management is handled efficiently, and
version control is maintained easily.
3. Creating Tables and Inserting Data
Creating tables and inserting data in SQLite is foundational to building a working database-
backed Android application.
### Creating Tables
Tables are created using standard SQL `CREATE TABLE` statements inside the `onCreate()`
method of your `SQLiteOpenHelper` subclass.
```java
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE students (id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT, age INTEGER);");
}
```
### Inserting Data
To insert data, use the `insert()` method of `SQLiteDatabase` class along with
`ContentValues`:
```java
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("age", 22);
long result = db.insert("students", null, values);
if (result == -1) {
Log.d("DB", "Insert failed");
} else {
Log.d("DB", "Insert successful");
}
```
### Notes
- Always use `ContentValues` to prevent SQL injection.
- Use transactions when inserting large amounts of data for performance.
Creating a table sets the schema, while insertion populates the database with actual records.
4. Inserting, Retrieving, and Updating Data
### Inserting
```java
ContentValues values = new ContentValues();
values.put("name", "Alice");
values.put("age", 23);
db.insert("students", null, values);
```
### Retrieving
```java
Cursor cursor = db.query("students", null, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
}
cursor.close();
```
### Updating
```java
ContentValues values = new ContentValues();
values.put("age", 24);
db.update("students", values, "name = ?", new String[]{"Alice"});
```
Inserting adds new records, retrieving fetches data using cursors, and updating modifies
specific records based on a condition.
5. Deleting Data in SQLite
Use `delete()` method to remove records.
### Delete a Record
```java
db.delete("students", "name = ?", new String[]{"Alice"});
```
### Delete All
```java
db.delete("students", null, null);
```
Always use `whereClause` to avoid deleting unintended data. Confirm rows deleted with the
return value.
6. Registering and Using Content Providers
A content provider is a component that manages access to a structured set of data. It's used
to share data between apps securely.
### Implementing
```java
public class MyProvider extends ContentProvider {
public boolean onCreate() { /* init db */ return true; }
public Cursor query(...) { /* return data */ }
public Uri insert(...) { /* insert data */ }
public int delete(...) { /* delete */ }
public int update(...) { /* update */ }
}
```
### Register in Manifest
```xml
<provider
android:name=".MyProvider"
android:authorities="com.example.provider"
android:exported="true"/>
```
### Use with ContentResolver
```java
getContentResolver().insert(CONTENT_URI, values);
Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);
```
Use content providers when you need to expose app data to other apps in a structured,
controlled manner.