Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Lọc dữ liệu SQLite Android với WHERE BETWEEN AND

Mục tiêu

Sử dụng mệnh đề WHERE column BETWEEN value1 AND value2 để lọc dữ liệu trong khoảng giá trị (inclusive - bao gồm cả 2 đầu).

Ví dụ thực tế

Lấy nhân viên có lương từ 10 đến 10.000 (đơn vị tùy ý).

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Layout (activity_main.xml) - Giống bài NOT IN

<?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"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText android:id="@+id/edtName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Tên" />
    <EditText android:id="@+id/edtSalary" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Lương" android:inputType="numberDecimal" />
    
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
        <Button android:id="@+id/btnSave" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Lưu" />
        <Button android:id="@+id/btnRefresh" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Làm mới (BETWEEN)" />
    </LinearLayout>

    <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />

</LinearLayout>

Bước 3: DatabaseHelper.java - Truy vấn BETWEEN

package com.example.sqlitebetween;

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 DB_NAME = "salaryDatabase3";
    private static final String TABLE_NAME = "SalaryDetails";
    private static final int VERSION = 1;

    DatabaseHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, name TEXT, salary TEXT)");
    }

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

    boolean insert(String name, String salary) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("salary", salary);
        return db.insert(TABLE_NAME, null, cv) != -1;
    }

    // TRUY VẤN CHÍNH: WHERE salary BETWEEN '10' AND '10000'
    ArrayList<String> getAllContacts() {
        SQLiteDatabase db = getReadableDatabase();
        ArrayList<String> list = new ArrayList<>();
        
        Cursor cursor = db.rawQuery(
            "SELECT * FROM " + TABLE_NAME + " WHERE salary BETWEEN '10' AND '10000'", 
            null
        );

        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return list;
    }
}

Bước 4: MainActivity.java (giống các bài trước)

package com.example.sqlitebetween;

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 {
    // ... code giống hệt bài NOT IN, chỉ khác tên package/class
    // Xem full code tại bài 1003060925
}

Giải thích BETWEEN ... AND

  • Inclusive: Bao gồm cả 2 giá trị đầu và cuối (>= value1 AND <= value2)
  • Tương đương: WHERE salary >= '10' AND salary <= '10000'
  • Thứ tự quan trọng: BETWEEN low AND high (low phải ≤ high)
  • Làm việc với: NUMBER, TEXT (so sánh lexicographic), DATE (định dạng ISO8601: YYYY-MM-DD)
  • Kết hợp với AND/OR: WHERE salary BETWEEN 10 AND 10000 AND name LIKE 'A%'

⚠️ Cảnh báo quan trọng: Kiểu dữ liệu TEXT

Trong ví dụ, cột salary là TEXT. So sánh TEXT theo thứ tự từ điển (lexicographic):

  • '100' < '20' → TRUE (vì '1' < '2')
  • '9' > '10000' → TRUE (vì '9' > '1')

Giải pháp: Luôn lưu số dưới kiểu INTEGER hoặc REAL:

CREATE TABLE ... (salary INTEGER) -- hoặc REAL cho số thập phân
INSERT ... VALUES (..., 5000) -- không quote số

Kết quả (với dữ liệu TEXT - có thể sai logic)

Nhập: ("A", "5"), ("B", "500"), ("C", "50000"), ("D", "100")
BETWEEN '10' AND '10000' (TEXT) → Kết quả có thể sai do so sánh chuỗi.

Lọc dữ liệu SQLite Android với WHERE BETWEEN AND

Best Practice

-- Schema đúng
CREATE TABLE SalaryDetails (
    id INTEGER PRIMARY KEY,
    name TEXT,
    salary INTEGER  -- KIỂU SỐ, KHÔNG PHẢI TEXT
);

-- Truy vấn an toàn
SELECT * FROM SalaryDetails WHERE salary BETWEEN 10 AND 10000;