Step 1 - Create The SQLite Database Helper Class
Step 1 - Create The SQLite Database Helper Class
7. Insert Data
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;
@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);
}
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;
}
}
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
textView.setText(builder.toString());
}
}
Ensure that your activity_main.xml layout file includes a TextView to display the data.
<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.