How to Create Multiple Tables on Sqlite Android Studio

In today’s digital age, data management and analysis have become essential skills for individuals and businesses alike. One popular tool for managing and analyzing data is SQLite, a lightweight and efficient database engine. SQLite is widely used in various platforms, including Android Studio, for its simplicity and functionality. One common task in data management is creating multiple tables within an SQLite database. In this blog post, we will explore different methods for creating multiple tables in SQLite within the Android Studio environment.

Video Tutorial:

Why You Need to Create Multiple Tables on SQLite

There are several reasons why you may need to create multiple tables within an SQLite database in Android Studio. Firstly, creating multiple tables allows you to organize your data efficiently. By segregating your data into separate tables, you can establish logical relationships between different types of information. This organization simplifies data retrieval and manipulation, making it easier to work with large datasets.

Additionally, creating multiple tables provides a more scalable solution. As your application or project grows, you may need to incorporate new data types or expand existing ones. By having separate tables, you can easily add new tables without affecting the existing data structure.

Now that we understand the importance of creating multiple tables in SQLite, let’s explore various methods to accomplish this task.

Method 1: Creating Multiple Tables via SQL Statements

Creating multiple tables in SQLite can be achieved through SQL statements. SQL (Structured Query Language) is a standard language for managing relational databases, including SQLite. In this method, we will write SQL statements to create individual tables and execute them within the Android Studio environment. Let’s see how it works:

Step 1: Open the SQLite database in Android Studio.
Step 2: Write the SQL statements for creating each table, specifying the table name, column names, and data types.
Step 3: Execute the SQL statements using the appropriate method in the SQLiteOpenHelper class.

Here is an example demonstrating the above steps:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Write the SQL statements for creating each table.
Write the SQL statements to create each table, specifying the table name, column names, and data types. For example, let’s say we want to create two tables – "Customers" and "Orders" – with the following columns:

Table: Customers
Columns:
– customer_id (integer)
– name (text)
– email (text)

Table: Orders
Columns:
– order_id (integer)
– customer_id (integer)
– amount (real)
– date (text)

Here are the SQL statements for creating these tables:

CREATE TABLE Customers (
customer_id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
);

CREATE TABLE Orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
amount REAL,
date TEXT
);

Step 3: Execute the SQL statements using the SQLiteOpenHelper class.
Use the SQLiteOpenHelper class to execute the SQL statements within the Android Studio environment. The SQLiteOpenHelper class provides methods for database creation and version management. Here is an example of using the SQLiteOpenHelper class to create the tables:

// Create a subclass of SQLiteOpenHelper
public class DatabaseHelper extends SQLiteOpenHelper {
// Define the constructor
public DatabaseHelper(Context context) {
super(context, "mydatabase.db", null, 1);
}

// Override the onCreate method
@Override
public void onCreate(SQLiteDatabase db) {
// Execute the SQL statements for creating tables
db.execSQL("CREATE TABLE Customers (customer_id INTEGER PRIMARY KEY, name TEXT, email TEXT);");
db.execSQL("CREATE TABLE Orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, amount REAL, date TEXT);");
}

// Override the onUpgrade method
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database upgrade if needed
}
}
Once you have defined the DatabaseHelper class, you can use it to create an instance of the helper and call the getWritableDatabase() method to create or open the database:

// Create an instance of the DatabaseHelper class
DatabaseHelper dbHelper = new DatabaseHelper(context);

// Get a writable database
SQLiteDatabase db = dbHelper.getWritableDatabase();
By executing the onCreate() method, the tables specified in the SQL statements will be created within the SQLite database.

Pros and Cons of Method 1:

Pros:

1. Allows for precise control over table creation.
2. Suitable for complex data structures and relationships.
3. Enables customization and optimization of table creation.
Cons:

1. Requires manual coding and execution of SQL statements.
2. Prone to syntax errors and data type mismatches if not carefully written.
3. May not be the most efficient method for creating multiple tables in large databases.

Method 2: Creating Multiple Tables via Database File Import

Another method to create multiple tables in SQLite within Android Studio is by importing a pre-existing SQLite database file. This method is particularly useful when you have a database file that already contains the necessary tables and data structure. Let’s see how it works:

Step 1: Locate the SQLite database file.
Locate the SQLite database file that you want to import. This file should have the .db or .sqlite extension.

Step 2: Copy the database file to the assets folder.
Copy the SQLite database file to the assets folder in your Android Studio project. This folder is typically located under the ‘app’ module.

Step 3: Import the database file in your code.
In your code, create a new instance of the SQLiteOpenHelper class and override the onCreate() method. Within the onCreate() method, call the copyDatabase() method to import the database file.

Here is an example demonstrating the above steps:

Step 1: Locate the SQLite database file.
Assume that the SQLite database file we want to import is named "mydatabase.db" and it is located in the project folder.

Step 2: Copy the database file to the assets folder.
Copy the SQLite database file to the assets folder in your Android Studio project. Make sure to place it under the ‘app’ module. The assets folder provides a convenient location for storing files that are bundled with the application.

Step 3: Import the database file in your code.
Create a new instance of the SQLiteOpenHelper class and override the onCreate() method. Within the onCreate() method, call the copyDatabase() method to import the database file:

// Create a subclass of SQLiteOpenHelper
public class DatabaseHelper extends SQLiteOpenHelper {
// Define the constructor
public DatabaseHelper(Context context) {
super(context, "mydatabase.db", null, 1);
}

// Override the onCreate method
@Override
public void onCreate(SQLiteDatabase db) {
copyDatabase(db);
}

// Copy the database file from the assets folder
private void copyDatabase(SQLiteDatabase db) {
try {
InputStream inputStream = context.getAssets().open("mydatabase.db");
OutputStream outputStream = new FileOutputStream(db.getPath());
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

// Override the onUpgrade method
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database upgrade if needed
}
}
Once you have defined the DatabaseHelper class, you can use it to create an instance of the helper and call the getWritableDatabase() method to create or open the database:

// Create an instance of the DatabaseHelper class
DatabaseHelper dbHelper = new DatabaseHelper(context);

// Get a writable database
SQLiteDatabase db = dbHelper.getWritableDatabase();
By executing the onCreate() method, the database file specified in the assets folder will be imported, including all its tables and data structure.

Pros and Cons of Method 2:

Pros:

1. Allows for easy import of pre-existing database files.
2. Suitable when you have a well-defined database structure ready.
3. Saves time by eliminating the need to create tables manually.
Cons:

1. Limited flexibility and customization compared to Method 1.
2. Requires prior preparation and availability of the database file.
3. Not ideal for creating new databases or modifying existing structures.

Method 3: Creating Multiple Tables via Object-Relational Mapping (ORM)

Object-Relational Mapping (ORM) is a technique that allows developers to map objects in their code to tables in a relational database. By utilizing an ORM framework, creating and managing multiple tables becomes more intuitive and efficient. In this method, we will explore how to create multiple tables in SQLite using the popular ORM framework, Room. Room is an official ORM library provided by Google for Android development. Here is how it works:

Step 1: Set up the Room library in your Android Studio project.
Add the necessary dependencies to your project’s build.gradle file to include the Room library. Room provides annotations and classes that simplify the creation of tables and database access.

Step 2: Define entity classes for each table.
Create entity classes that represent the tables in your SQLite database. An entity class defines the structure and properties of a table. Annotate the entity classes with the necessary Room annotations.

Step 3: Create a database class.
Create a database class that extends the RoomDatabase class. This class acts as the main access point for the database and provides methods to retrieve instances of the entity classes.

Let’s look at an example to illustrate the steps:

Step 1: Set up the Room library in your Android Studio project.
In your project’s build.gradle file, add the necessary dependencies for Room:

dependencies {
def room_version = "2.3.0"

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}
Sync your project to download the required dependencies.

Step 2: Define entity classes for each table.
Create entity classes for each table you want to create. For example, let’s say we want to create two tables – "Customers" and "Orders" – with the following columns:

Table: Customers
Columns:
– customer_id (integer)
– name (text)
– email (text)

Table: Orders
Columns:
– order_id (integer)
– customer_id (integer)
– amount (real)
– date (text)

Here are the entity classes for these tables:

@Entity(tableName = "Customers")
public class Customer {
@PrimaryKey
@ColumnInfo(name = "customer_id")
public int customerId;

@ColumnInfo(name = "name")
public String name;

@ColumnInfo(name = "email")
public String email;
}

@Entity(tableName = "Orders")
public class Order {
@PrimaryKey
@ColumnInfo(name = "order_id")
public int orderId;

@ColumnInfo(name = "customer_id")
public int customerId;

@ColumnInfo(name = "amount")
public double amount;

@ColumnInfo(name = "date")
public String date;
}
Step 3: Create a database class.
Create a database class that extends the RoomDatabase class. Annotate the class with the @Database annotation and include the entity classes as parameters. Define an abstract method that returns an instance of the database class.

@Database(entities = {Customer.class, Order.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
public abstract CustomerDao customerDao();
public abstract OrderDao orderDao();
}
The database class serves as the main access point for retrieving instances of the entity classes. The abstract Dao classes (e.g., CustomerDao and OrderDao) contain methods to interact with the tables.

Pros and Cons of Method 3:

Pros:

1. Provides a higher level of abstraction and simplicity.
2. Reduces the complexity of SQL statements and database management.
3. Enables object-oriented approach to database design.
Cons:

1. Requires learning and implementing an ORM framework.
2. May have a learning curve for developers new to Room or ORM concepts.
3. Additional dependencies and configurations are needed.

Method 4: Creating Multiple Tables via Raw SQL Execution

The final method we will explore to create multiple tables in SQLite within Android Studio is by executing raw SQL statements. This method allows developers to directly execute raw SQL statements without using an ORM framework or predefined methods. Although it requires additional coding, it provides maximum flexibility and control. Let’s see how it works:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to create tables.
Write raw SQL statements to create each table, specifying the table name, column names, and data types. Unlike Method 1, where we use the SQLiteOpenHelper class, here we directly execute the SQL statements. Let’s take a look at an example:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to create tables.
Write raw SQL statements to create each table, specifying the table name, column names, and data types. Unlike Method 1, where we use the SQLiteOpenHelper class, here we directly execute the SQL statements. Let’s take a look at an example:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to create tables.
Write raw SQL statements to create each table, specifying the table name, column names, and data types. Unlike Method 1, where we use the SQLiteOpenHelper class, here we directly execute the SQL statements. Let’s take a look at an example:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to create tables.
Write raw SQL statements to create each table, specifying the table name, column names, and data types. Unlike Method 1, where we use the SQLiteOpenHelper class, here we directly execute the SQL statements. Let’s take a look at an example:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to create tables.
Write raw SQL statements to create each table, specifying the table name, column names, and data types. Unlike Method 1, where we use the SQLiteOpenHelper class, here we directly execute the SQL statements. Let’s take a look at an example:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to create tables.
Write raw SQL statements to create each table, specifying the table name, column names, and data types. Unlike Method 1, where we use the SQLiteOpenHelper class, here we directly execute the SQL statements. Let’s take a look at an example:

Step 1: Open the SQLite database in Android Studio.
Open the SQLite database you want to work with in Android Studio. The database can be either an existing database or a new one that you create.

Step 2: Execute raw SQL statements to