0% found this document useful (0 votes)
20 views5 pages

SQLite Course Management App Code

The document shows code for an Android app that uses a SQLite database to store course data. It defines a DBHandler class that extends SQLiteOpenHelper to manage the database. The onCreate() method creates a database table with columns for course ID, name, duration, description and tracks. The addNewCourse() method inserts a new course into the table. The MainActivity gets input from EditTexts, calls addNewCourse() and displays a toast on success.

Uploaded by

ukbalaji_it
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views5 pages

SQLite Course Management App Code

The document shows code for an Android app that uses a SQLite database to store course data. It defines a DBHandler class that extends SQLiteOpenHelper to manage the database. The onCreate() method creates a database table with columns for course ID, name, duration, description and tracks. The addNewCourse() method inserts a new course into the table. The MainActivity gets input from EditTexts, calls addNewCourse() and displays a toast on success.

Uploaded by

ukbalaji_it
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Navigate to the app > java > your app’s package name > Right-click on it

> New > Java class and name it as DBHandler and add the below code
import [Link];

import [Link];

import [Link];

import [Link];

public class DBHandler extends SQLiteOpenHelper {

private static final String DB_NAME = "coursedb";

private static final int DB_VERSION = 1;

private static final String TABLE_NAME = "mycourses";

private static final String ID_COL = "id";

private static final String NAME_COL = "name";

private static final String DURATION_COL = "duration";

private static final String DESCRIPTION_COL = "description";

private static final String TRACKS_COL = "tracks";

public DBHandler(Context context) {

super(context, DB_NAME, null, DB_VERSION);

// below method is for creating a database by running a sqlite query

@Override

public void onCreate(SQLiteDatabase db) {

String query = "CREATE TABLE " + TABLE_NAME + " ("

+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "

+ NAME_COL + " TEXT,"

+ DURATION_COL + " TEXT,"

+ DESCRIPTION_COL + " TEXT,"


+ TRACKS_COL + " TEXT)";

[Link](query);

// this method is use to add new course to our sqlite database.

public void addNewCourse(String courseName, String courseDuration, String


courseDescription, String courseTracks) {

SQLiteDatabase db = [Link]();

ContentValues values = new ContentValues();

[Link](NAME_COL, courseName);

[Link](DURATION_COL, courseDuration);

[Link](DESCRIPTION_COL, courseDescription);

[Link](TRACKS_COL, courseTracks);

[Link](TABLE_NAME, null, values);

[Link]();

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// this method is called to check if the table exists already.

[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);

onCreate(db);

}
[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

// creating variables for our edittext, button and dbhandler

private EditText courseNameEdt, courseTracksEdt, courseDurationEdt,


courseDescriptionEdt;

private Button addCourseBtn;

private DBHandler dbHandler;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

// initializing all our variables.

courseNameEdt = findViewById([Link]);

courseTracksEdt = findViewById([Link]);

courseDurationEdt = findViewById([Link]);

courseDescriptionEdt = findViewById([Link]);

addCourseBtn = findViewById([Link]);
// creating a new dbhandler class

// and passing our context to it.

dbHandler = new DBHandler([Link]);

// below line is to add on click listener for our add course button.

[Link](new [Link]() {

@Override

public void onClick(View v) {

// below line is to get data from all edit text fields.

String courseName = [Link]().toString();

String courseTracks = [Link]().toString();

String courseDuration = [Link]().toString();

String courseDescription = [Link]().toString();

// validating if the text fields are empty or not.

if ([Link]() && [Link]() &&


[Link]() && [Link]()) {

[Link]([Link], "Please enter all the


data..", Toast.LENGTH_SHORT).show();

return;

// on below line we are calling a method to add new

// course to sqlite data and pass all our values to it.

[Link](courseName, courseDuration,
courseDescription, courseTracks);
// after adding the data we are displaying a toast message.

[Link]([Link], "Course has been added.",


Toast.LENGTH_SHORT).show();

[Link]("");

[Link]("");

[Link]("");

[Link]("");

});

<EditText
android:id="@+id/idEdtCourseName"
<EditText
android:id="@+id/idEdtCourseDuration"
<EditText
android:id="@+id/idEdtCourseTracks"
<EditText
android:id="@+id/idEdtCourseDescription"
<Button
android:id="@+id/idBtnAddCourse"

Common questions

Powered by AI

The onUpgrade() method in the DBHandler class is crucial for managing changes in the database schema when the application version changes. This method is invoked when the database version number is incremented. It drops the existing table with "DROP TABLE IF EXISTS" and recreates it using onCreate(), ensuring the database is in sync with the latest schema requirements. This contributes to application maintenance by allowing developers to smoothly transition between different schema versions and avoid issues related to outdated or incompatible database structures .

User interactions are captured and managed in the MainActivity class by first initializing EditText fields and a Button for input and actions, respectively. An onClick listener is assigned to the addCourseBtn. When clicked, this listener retrieves data entered by the user into EditText components, validates these fields to ensure they are not empty, and calls the addNewCourse() function of the DBHandler to insert this data into the database. The system provides feedback through a Toast message once the course is successfully added, and then resets the input fields for further use .

SQLiteOpenHelper is utilized in the DBHandler class as a base class providing utility methods for database management. Its role includes handling database creation using the onCreate() method, which is triggered the first time the database is accessed. It assists in handling database version management through the onUpgrade() method, allowing developers to define actions when the database scheme changes. SQLiteOpenHelper abstracts repetitive tasks associated with database management, allowing developers to focus on specific queries and operations instead .

Data validation in the provided Android application is handled in the MainActivity class. Before inserting courses into the SQLite database, user input is retrieved from EditText fields. An onClick listener for the addCourseBtn checks whether any field is empty by using isEmpty() on strings retrieved from the respective EditText fields. If any field is empty, a Toast message prompts the user to "Please enter all the data." If all fields are populated, the validated data is passed to the DBHandler's addNewCourse() method for insertion .

The application ensures the database connection is maintained and closed properly by opening a writable database connection using getWritableDatabase() within methods like addNewCourse(). After executing database operations such as inserting values, the class explicitly calls db.close() to close the database connection. This practice prevents database locks, reduces resource consumption, and avoids potential memory leaks by ensuring that database resources are promptly released after use .

In a multi-threaded Android environment, using SQLiteOpenHelper can present several challenges. Managing concurrent database access across different threads can lead to unexpected behavior, such as deadlocks, data conflicts, and corrupted databases. SQLiteDatabase instances are not inherently thread-safe. Transactions from multiple threads may overlap, causing synchronization issues. Developers must ensure database operations are serialized appropriately or use synchronization mechanisms. Additionally, improperly closing database connections could lead to memory leaks or resource contention. Careful management of database lifecycle and thread synchronization is essential to prevent these issues .

Failing to implement appropriate data validation before adding entries to an SQLite database in Android applications can have several implications. It can lead to the insertion of incomplete or incorrect data into the database, which may cause logical errors and inconsistent data records. This can affect the integrity and reliability of the application's data. Additionally, without validation, the application may crash or behave unexpectedly if assumptions about the presence of data are violated, leading to poor user experience and potential data loss .

To modify the onCreate method in DBHandler for adding a new column to store course difficulty levels, you would update the SQL CREATE TABLE statement within the onCreate() method. The updated query should include a new column for difficulty, probably defined similarly to the existing columns, such as 'difficulty TEXT'. This query will look like: 'CREATE TABLE mycourses (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, duration TEXT, description TEXT, tracks TEXT, difficulty TEXT)'. This change would necessitate an onUpgrade() method implementation that correctly handles transitioning to this new schema without data loss .

The DBHandler class facilitates interaction with SQLite databases by extending SQLiteOpenHelper, which provides utilities for managing database creation and version management. Key methods include onCreate() to setup the database table structure with a SQL query, addNewCourse() to insert new records into the table by using SQLiteDatabase in write mode and ContentValues to hold values, and onUpgrade() to manage database schema changes by dropping existing tables and calling onCreate() for a fresh setup .

The components involved in creating and using an SQLite database in an Android application include the DBHandler class and the MainActivity. The DBHandler class extends SQLiteOpenHelper and defines constants for database names, table names, and column names. The onCreate() method runs a SQLite query to create a table with columns for id, name, duration, description, and tracks. The addNewCourse() method inserts new course data into the database using ContentValues. The MainActivity initializes views and the DBHandler instance, retrieves user input from EditText fields, validates the input, and calls the DBHandler's addNewCourse() method to insert the data. Once data is successfully added, a Toast message confirms the operation .

You might also like