Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ IS NOT NULL ใน SQLite Android

ภาพรวม

SQLite เป็นฐานข้อมูล SQL แบบ Open Source ที่เก็บข้อมูลในไฟล์ข้อความบนอุปกรณ์ Android มี SQLite ในตัว (Built-in) รองรับฟีเจอร์ฐานข้อมูลเชิงสัมพันธ์ครบถ้วน ไม่ต้องตั้งค่า Connection เหมือน JDBC/ODBC

ตัวอย่างนี้สาธิตการใช้เงื่อนไข IS NOT NULL ในคำสั่ง SQLite เพื่อกรองข้อมูลที่ไม่ใช่ค่าว่าง

ขั้นตอนการสร้าง

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → กรอกรายละเอียด

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (res/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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ป้อนชื่อ" />

    <EditText
        android:id="@+id/salary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:hint="ป้อนเงินเดือน" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/save"
            android:text="บันทึก"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/refresh"
            android:text="รีเฟรช"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/update"
            android:text="อัปเดต"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

มี EditText 2 ช่องสำหรับชื่อและเงินเดือน ปุ่มบันทึกเก็บข้อมูลลง SQLite ปุ่มรีเฟรชอัปเดต ListView จาก Cursor พร้อมเงื่อนไข NOT NULL ปุ่มอัปเดตแก้ไขข้อมูล

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    Button save, refresh;
    EditText name, salary;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final DatabaseHelper helper = new DatabaseHelper(this);
        final ArrayList<String> arrayList = helper.getAllContacts();

        name = findViewById(R.id.name);
        salary = findViewById(R.id.salary);
        listView = findViewById(R.id.listView);

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
            this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(arrayAdapter);

        findViewById(R.id.refresh).setOnClickListener(v -> {
            arrayList.clear();
            arrayList.addAll(helper.getAllContacts());
            arrayAdapter.notifyDataSetChanged();
            listView.invalidateViews();
            listView.refreshDrawableState();
        });

        findViewById(R.id.save).setOnClickListener(v -> {
            String nameStr = name.getText().toString().trim();
            String salaryStr = salary.getText().toString().trim();

            if (!nameStr.isEmpty() && !salaryStr.isEmpty()) {
                if (helper.insert(nameStr, salaryStr)) {
                    Toast.makeText(this, "บันทึกสำเร็จ", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "บันทึกไม่สำเร็จ", Toast.LENGTH_LONG).show();
                }
            } else {
                name.setError("กรุณาป้อนชื่อ");
                salary.setError("กรุณาป้อนเงินเดือน");
            }
        });
    }
}

ขั้นตอนที่ 4: สร้าง DatabaseHelper (src/DatabaseHelper.java)

package com.example.andy.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
import java.util.ArrayList;

class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "salaryDatabase5";
    public static final String CONTACTS_TABLE_NAME = "SalaryDetails";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL("CREATE TABLE " + CONTACTS_TABLE_NAME + 
                "(id INTEGER PRIMARY KEY, name TEXT, salary TEXT, datetime DEFAULT CURRENT_TIMESTAMP)");
        } catch (SQLiteException e) {
            try { throw new IOException(e); } 
            catch (IOException e1) { e1.printStackTrace(); }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);
        onCreate(db);
    }

    public boolean insert(String name, String salary) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("salary", salary);
        db.replace(CONTACTS_TABLE_NAME, null, values);
        return true;
    }

    public ArrayList<String> getAllContacts() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<String> arrayList = new ArrayList<>();
        
        // ใช้ IS NOT NULL ร่วมกับเงื่อนไขอื่น
        Cursor res = db.rawQuery(
            "SELECT * FROM " + CONTACTS_TABLE_NAME + 
            " WHERE name = 'sairam' AND name IS NOT NULL", null);
        
        res.moveToFirst();
        while (!res.isAfterLast()) {
            arrayList.add(res.getString(res.getColumnIndex("name")));
            res.moveToNext();
        }
        res.close(); // สำคัญ: ปิด Cursor
        return arrayList;
    }

    public boolean update(String name, String salary) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("UPDATE " + CONTACTS_TABLE_NAME + 
            " SET name = '" + name + "', salary = '" + salary + "'");
        return true;
    }

    public boolean delete() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM " + CONTACTS_TABLE_NAME);
        return true;
    }
}

การทดสอบ

รันแอปพลิเคชัน จะแสดงเฉพาะข้อมูลที่ name = 'sairam' และไม่เป็น NULL

วิธีใช้ IS NOT NULL ใน SQLite Android

ความรู้เพิ่มเติมเกี่ยวกับ NULL ใน SQLite

ความแตกต่างระหว่าง NULL, Empty String, และ Zero

-- NULL: ไม่มีค่า (Unknown)
INSERT INTO test (col) VALUES (NULL);

-- Empty String: มีค่าแต่เป็นสตริงว่าง
INSERT INTO test (col) VALUES ('');

-- Zero: ค่าตัวเลขศูนย์
INSERT INTO test (col) VALUES (0);

การตรวจสอบ NULL อย่างถูกต้อง

-- ถูกต้อง
WHERE column IS NULL
WHERE column IS NOT NULL

-- ผิด (จะไม่ทำงานเพราะ NULL != NULL ใน SQL)
WHERE column = NULL
WHERE column != NULL
WHERE column <> NULL

ฟังก์ชันจัดการ NULL

-- COALESCE: คืนค่าแรกที่ไม่ใช่ NULL
SELECT COALESCE(name, 'Unknown') FROM users;

-- IFNULL: เฉพาะ SQLite (2 arguments)
SELECT IFNULL(name, 'Unknown') FROM users;

-- NULLIF: คืน NULL ถ้าค่าทั้งสองเท่ากัน
SELECT NULLIF(name, '') FROM users; -- คืน NULL ถ้า name เป็น empty string

Best Practices

  • ใช้ IS NULL / IS NOT NULL เสมอสำหรับการตรวจสอบ NULL
  • ปิด Cursor หลังใช้งานเสร็จ (cursor.close())
  • ใช้ Parameterized Query ป้องกัน SQL Injection
  • พิจารณาใช้ Room Database แทน Raw SQLite สำหรับโปรเจกต์ใหม่