Tổng quan về SQLite trong Android
SQLite là cơ sở dữ liệu SQL mã nguồn mở, lưu trữ dữ liệu trong file văn bản trên thiết bị. Android tích hợp sẵn SQLite, hỗ trợ đầy đủ các tính năng cơ sở dữ liệu quan hệ. Không cần thiết lập kết nối như JDBC hay ODBC để truy cập.
Mục tiêu
Ví dụ này minh họa cách sử dụng toán tử AND trong truy vấn SQLite để lọc dữ liệu theo nhiều điều kiện cùng lúc.
Các bước thực hiện
Bước 1: Tạo dự án mới
Trong Android Studio, chọn File → New Project và hoàn tất các thông tin cần thiết.
Bước 2: Thiết kế giao diện (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nhập tên" />
<EditText
android:id="@+id/edtSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nhập lương"
android:inputType="numberDecimal" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lưu" />
<Button
android:id="@+id/btnRefresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Làm mới" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Giao diện bao gồm 2 ô nhập liệu (tên, lương), 2 nút bấm (Lưu, Làm mới) và ListView hiển thị kết quả lọc bằng toán tử AND.
Bước 3: Code MainActivity.java
package com.example.sqliteandoperator;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button btnSave, btnRefresh;
private EditText edtName, edtSalary;
private ListView listView;
private DatabaseHelper helper;
private ArrayList<String> dataList;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new DatabaseHelper(this);
dataList = helper.getAllContacts();
edtName = findViewById(R.id.edtName);
edtSalary = findViewById(R.id.edtSalary);
listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
btnRefresh = findViewById(R.id.btnRefresh);
btnRefresh.setOnClickListener(v -> {
dataList.clear();
dataList.addAll(helper.getAllContacts());
adapter.notifyDataSetChanged();
listView.invalidateViews();
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(v -> {
String name = edtName.getText().toString().trim();
String salary = edtSalary.getText().toString().trim();
if (!name.isEmpty() && !salary.isEmpty()) {
if (helper.insert(name, salary)) {
Toast.makeText(this, "Đã thêm", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Thêm thất bại", Toast.LENGTH_LONG).show();
}
} else {
if (name.isEmpty()) edtName.setError("Nhập tên");
if (salary.isEmpty()) edtSalary.setError("Nhập lương");
}
});
}
}
Bước 4: Tạo DatabaseHelper.java
package com.example.sqliteandoperator;
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;
class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "salaryDatabase";
private static final String TABLE_NAME = "SalaryDetails";
private static final int VERSION = 1;
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME +
" (id INTEGER PRIMARY KEY, name TEXT, salary TEXT)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
boolean insert(String name, String salary) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("salary", salary);
long result = db.insert(TABLE_NAME, null, values);
return result != -1;
}
ArrayList<String> getAllContacts() {
SQLiteDatabase db = getReadableDatabase();
ArrayList<String> list = new ArrayList<>();
// Sử dụng toán tử AND: lương > 10 VÀ tên bắt đầu bằng "Sa"
Cursor cursor = db.rawQuery(
"SELECT * FROM " + TABLE_NAME + " WHERE salary > '10' AND name LIKE 'Sa%'",
null
);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
}
Giải thích truy vấn SQL
Câu lệnh WHERE salary > '10' AND name LIKE 'Sa%' chỉ trả về các bản ghi thỏa mãn cả hai điều kiện:
- Cột
salarylớn hơn 10 - Cột
namebắt đầu bằng chuỗi "Sa" (ví dụ: "Sam", "Sarah", "Sandy")
Chạy và kiểm tra
Chạy ứng dụng, nhập một số dữ liệu mẫu (ví dụ: "Sam - 15", "Sarah - 20", "John - 5", "Sandy - 8"). Nhấn nút Làm mới, ListView sẽ chỉ hiển thị "Sam" và "Sarah" vì chúng thỏa mãn cả 2 điều kiện.

Danh sách chỉ hiển thị tên có lương > 10 và tên bắt đầu bằng "Sa".