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

Lọc dữ liệu SQLite Android với WHERE NOT IN

Mục tiêu

Sử dụng mệnh đề WHERE ... NOT IN trong SQLite Android để loại trừ các bản ghi có giá trị nằm trong danh sách cho trước.

Ví dụ thực tế

Lấy danh sách nhân viên có lương KHÔNG nằm trong tập {10, 10000} (ví dụ: loại trừ lương tối thiểu và tối đa).

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)

<?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="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="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 (NOT IN)" />

    </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 - QUAN TRỌNG

package com.example.sqlitenotin;

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 = "salaryDatabase";
    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 NOT IN ('10', '10000')
    ArrayList<String> getAllContacts() {
        SQLiteDatabase db = getReadableDatabase();
        ArrayList<String> list = new ArrayList<>();
        
        Cursor cursor = db.rawQuery(
            "SELECT * FROM " + TABLE_NAME + " WHERE salary NOT IN ('10', '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

package com.example.sqlitenotin;

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 EditText edtName, edtSalary;
    private Button btnSave, btnRefresh;
    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);
        btnSave = findViewById(R.id.btnSave);
        btnRefresh = findViewById(R.id.btnRefresh);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);

        btnRefresh.setOnClickListener(v -> {
            dataList.clear();
            dataList.addAll(helper.getAllContacts());
            adapter.notifyDataSetChanged();
        });

        btnSave.setOnClickListener(v -> {
            String name = edtName.getText().toString().trim();
            String salary = edtSalary.getText().toString().trim();
            if (name.isEmpty() || salary.isEmpty()) {
                if (name.isEmpty()) edtName.setError("Nhập tên");
                if (salary.isEmpty()) edtSalary.setError("Nhập lương");
                return;
            }
            if (helper.insert(name, salary)) {
                Toast.makeText(this, "Đã thêm", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Thêm thất bại", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Giải thích NOT IN

Cú pháp: WHERE column NOT IN (value1, value2, ...)

  • Trả về TRUE nếu giá trị column không khớp với bất kỳ giá trị nào trong danh sách
  • Tương đương: WHERE column != value1 AND column != value2 AND ...
  • Danh sách có thể là subquery: WHERE id NOT IN (SELECT id FROM other_table)
  • Lưu ý: Nếu danh sách chứa NULL, NOT IN luôn trả về UNKNOWN (không trả về row nào) → tránh NULL trong danh sách

Kết quả

Nhập dữ liệu: ("A", "10"), ("B", "5000"), ("C", "10000"), ("D", "20000")
Nhấn "Làm mới" → ListView chỉ hiển thị: B, D (lương 5000 và 20000 không nằm trong {10, 10000})

Lọc dữ liệu SQLite Android với WHERE NOT IN

Các toán tử liên quan

  • IN: Trong danh sách
  • NOT IN: Không trong danh sách
  • BETWEEN: Trong khoảng
  • LIKE: Khớp mẫu (pattern)
  • GLOB: Khớp mẫu Unix wildcard