Android Database Demo: A Simple Example
This blog post provides a complete demo of an Android app that uses a SQLite database. The demo includes the Java code for the activity, the XML layout files for the UI and gradient background, and the database helper class. All code is presented in attractive, easy-to-read boxes.
1. MainActivity.java
// package declaration package com.tecvipul.databasedemo; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText editTextName, editTextAge; Button btnAdd, btnView, btnUpdate, btnDelete; TextView textViewData; DatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextName = findViewById(R.id.editTextName); editTextAge = findViewById(R.id.editTextAge); btnAdd = findViewById(R.id.btnAdd); btnView = findViewById(R.id.btnView); btnUpdate = findViewById(R.id.btnUpdate); btnDelete = findViewById(R.id.btnDelete); textViewData = findViewById(R.id.textViewData); dbHelper = new DatabaseHelper(this); btnAdd.setOnClickListener(view -> { String name = editTextName.getText().toString(); String age = editTextAge.getText().toString(); if (!name.isEmpty() && !age.isEmpty()) { boolean inserted = dbHelper.insertData(name, Integer.parseInt(age)); Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Filled can not be empty", Toast.LENGTH_SHORT).show(); } }); btnView.setOnClickListener(view -> { Cursor cursor = dbHelper.getAllData(); if (cursor.getCount() == 0) { textViewData.setText("No data found"); return; } StringBuilder builder = new StringBuilder(); while (cursor.moveToNext()) { builder.append("ID: ").append(cursor.getString(0)) .append("\nName: ").append(cursor.getString(1)) .append("\nAge: ").append(cursor.getString(2)) .append("\n\n"); } textViewData.setText(builder.toString()); }); btnUpdate.setOnClickListener(view -> { String id = editTextName.getText().toString(); String age = editTextAge.getText().toString(); if (!id.isEmpty() && !age.isEmpty()) { boolean updated = dbHelper.updateData(id, Integer.parseInt(age)); Toast.makeText(getApplicationContext(), "Data Updated", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Enter ID and new Age", Toast.LENGTH_SHORT).show(); } }); btnDelete.setOnClickListener(view -> { String id = editTextName.getText().toString(); if (!id.isEmpty()) { boolean deleted = dbHelper.deleteData(id); Toast.makeText(getApplicationContext(), "Data Deleted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Enter ID to delete", Toast.LENGTH_SHORT).show(); } }); } }
2. XML Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg_layout" android:gravity="center" android:orientation="vertical" android:padding="16dp"> <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name / Enter ID for delete or update"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:hint="Enter Age"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.button.MaterialButton android:id="@+id/btnAdd" style="@style/Widget.MaterialComponents.Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:backgroundTint="#2196F3" android:text="Add Record" android:textColor="#FFFFFF" /> <com.google.android.material.button.MaterialButton android:id="@+id/btnView" style="@style/Widget.MaterialComponents.Button.OutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:text="View Records" /> <com.google.android.material.button.MaterialButton android:id="@+id/btnUpdate" style="@style/Widget.MaterialComponents.Button.OutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:text="Update Record" /> <com.google.android.material.button.MaterialButton android:id="@+id/btnDelete" style="@style/Widget.MaterialComponents.Button.OutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:text="Delete Record" /> <TextView android:id="@+id/textViewData" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:background="#E0E0E0" android:padding="10dp" android:text="Data will be shown here" android:textSize="16sp" /> </LinearLayout> </ScrollView>
3. Gradient Drawable (bg_layout.xml)
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <gradient android:angle="45" android:startColor="#FFDAB9" android:centerColor="#87CEFA" android:endColor="#FFC0CB" android:type="linear" /> </shape> </item> </layer-list>
4. DatabaseHelper.java
package com.tecvipul.databasedemo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "UserDB"; private static final String TABLE_NAME = "Users"; private static final String COL_ID = "ID"; private static final String COL_NAME = "Name"; private static final String COL_AGE = "Age"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } public boolean insertData(String name, int age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_NAME, name); values.put(COL_AGE, age); long result = db.insert(TABLE_NAME, null, values); return result != -1; } public Cursor getAllData() { SQLiteDatabase db = this.getReadableDatabase(); return db.rawQuery("SELECT * FROM " + TABLE_NAME, null); } public boolean updateData(String id, int age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_AGE, age); int result = db.update(TABLE_NAME, values, "ID = ?", new String[]{id}); return result > 0; } public boolean deleteData(String id) { SQLiteDatabase db = this.getWritableDatabase(); int result = db.delete(TABLE_NAME, "ID = ?", new String[]{id}); return result > 0; } }
Detailed Description
MainActivity.java: This is the primary activity file where all the UI interactions are handled. It initializes the UI components, sets up button click listeners, and performs database operations like adding, viewing, updating, and deleting records.
activity_main.xml: This XML file defines the user interface. It uses a ScrollView
to ensure the layout is scrollable. The UI elements include text fields for entering a name (or ID) and age, buttons for database actions, and a TextView
for displaying database records.
bg_layout.xml (Gradient Drawable): This XML file creates an attractive background using a gradient that transitions between light orange, light blue, and light pink. It is applied to the main layout to enhance the visual appearance.
DatabaseHelper.java: This class manages the SQLite database. It includes methods for creating the database table, and performing CRUD (Create, Read, Update, Delete) operations. The class ensures a smooth interaction between the app and the underlying database.
Together, these files form a simple Android database demo application that is both easy to understand and visually appealing. This post provides a hands-on example for beginners to learn how to implement a SQLite database in an Android application.
0 Comments
If you have any doubts, Please let me know