0% found this document useful (0 votes)
11 views

Step 1 - Create The SQLite Database Helper Class

Uploaded by

Good
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Step 1 - Create The SQLite Database Helper Class

Uploaded by

Good
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

STEPS

1. PREPARE CREATE TABLE SQL QUERY

2. CREATE DbHelper Class =>DbHelper extends SqliteOpenHelper

3. Override OnCreate() & onUpgrade()

4. Create Constructor Matching Super

5.Inside onCreate write Create Table Query

6. In Your MainActivity Create DbHelper Object & Pass Context To


Constructor

7. Insert Data

Step 1: Create the SQLite Database Helper Class

Create a new Java class named DatabaseHelper. This class will extend
SQLiteOpenHelper and will handle the creation, upgrading, and querying of the database.

java
Copy code
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mydatabase.db";


private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY
AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_AGE + " INTEGER)";
db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

// Method to insert a new person


public void addPerson(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_AGE, age);

db.insert(TABLE_NAME, null, values);


db.close();
}

// Method to get all persons as an ArrayList


public ArrayList<Person> getAllPersons() {
ArrayList<Person> persons = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);

if (cursor.moveToFirst()) {
do {
int id =
cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
String name =
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME));
int age =
cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_AGE));
persons.add(new Person(id, name, age));
} while (cursor.moveToNext());
}
cursor.close();
db.close();

return persons;
}
}

Step 2: Create the Person Model Class

Create a simple Person class to represent the data model.

public class Person {


private int id;
private String name;
private int age;

public Person(int id, String name, int age) {


this.id = id;
this.name = name;
this.age = age;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

Step 3: Use the Database Helper in Your Activity

In your MainActivity, create an instance of DatabaseHelper and use it to add and


retrieve data.

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private DatabaseHelper dbHelper;


private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

dbHelper = new DatabaseHelper(this);


textView = findViewById(R.id.textView);

// Insert some data


dbHelper.addPerson("John Doe", 30);
dbHelper.addPerson("Jane Smith", 25);

// Retrieve and display data


ArrayList<Person> persons = dbHelper.getAllPersons();
StringBuilder builder = new StringBuilder();

for (Person person : persons) {


builder.append("ID: ").append(person.getId())
.append(", Name: ").append(person.getName())
.append(", Age:
").append(person.getAge()).append("\n");
}

textView.setText(builder.toString());
}
}

Step 4: Update Layout XML

Ensure that your activity_main.xml layout file includes a TextView to display the data.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="16sp" />
</RelativeLayout>

Explanation of Code

1. DatabaseHelper Class:
○ onCreate(): Creates the table when the database is first created.
○ onUpgrade(): Handles database schema changes.
○ addPerson(): Inserts a new row into the table.
○ getAllPersons(): Retrieves all rows from the table and returns them as an
ArrayList of Person objects.
2. Person Class:
○ A simple data model class with fields for id, name, and age, along with their
getters and setters.
3. MainActivity Class:
○ onCreate(): Initializes the DatabaseHelper, inserts some data, retrieves
data, and displays it in a TextView.

By following these steps, you create an Android application that uses SQLite for data
storage and retrieval. The DatabaseHelper class manages the database operations, and
the MainActivity demonstrates how to use this helper class to interact with the database
and display the retrieved data.

You might also like