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

Cách sử dụng hàm cast() trong SQLite Android

Giới thiệu về SQLite trong Android

SQLite là một 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ủa 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 cơ sở dữ liệu này.

Ví dụ: Sử dụng cast() để chuyển đổi kiểu dữ liệu

Hàm cast() trong SQLite cho phép chuyển đổi giá trị từ kiểu dữ liệu này sang kiểu khác. Trong ví dụ này, chúng ta sẽ lưu lương dưới dạng float nhưng hiển thị dưới dạng số nguyên (int) bằng cast(salary as int).

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (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:hint="Nhập tên"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/salary"
        android:layout_width="match_parent"
        android:inputType="numberDecimal"
        android:hint="Nhập lương"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/save"
            android:text="Lưu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/refresh"
            android:text="Làm mới"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/update"
            android:text="Cập nhật"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/delete"
            android:text="Xóa tất cả"
            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">
    </ListView>
</LinearLayout>

Bước 3: Code MainActivity.java

package com.example.castdemo;

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 {
    Button save, refresh, update, delete;
    EditText name, salary;
    ArrayAdapter<String> arrayAdapter;
    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);

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

        findViewById(R.id.delete).setOnClickListener(v -> {
            if (helper.delete()) {
                Toast.makeText(this, "Đã xóa", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Xóa thất bại", Toast.LENGTH_LONG).show();
            }
        });

        findViewById(R.id.update).setOnClickListener(v -> {
            String n = name.getText().toString().trim();
            String s = salary.getText().toString().trim();
            if (!n.isEmpty() && !s.isEmpty()) {
                if (helper.update(n, s)) {
                    Toast.makeText(this, "Đã cập nhật", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "Cập nhật thất bại", Toast.LENGTH_LONG).show();
                }
            } else {
                name.setError("Nhập tên");
                salary.setError("Nhập lương");
            }
        });

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

        findViewById(R.id.save).setOnClickListener(v -> {
            String n = name.getText().toString().trim();
            String s = salary.getText().toString().trim();
            if (!n.isEmpty() && !s.isEmpty()) {
                if (helper.insert(n, s)) {
                    Toast.makeText(this, "Đã thêm", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "Thêm thất bại", Toast.LENGTH_LONG).show();
                }
            } else {
                name.setError("Nhập tên");
                salary.setError("Nhập lương");
            }
        });
    }
}

Bước 4: Code DatabaseHelper.java - Điểm quan trọng

package com.example.castdemo;

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 {
    static final String DATABASE_NAME = "salaryDatabase";
    static final String TABLE_NAME = "SalaryDetails";

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

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

    @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);
        db.insert(TABLE_NAME, null, values);
        return true;
    }

    // Sử dụng CAST() để chuyển salary từ float sang int khi hiển thị
    ArrayList<String> getAllContacts() {
        SQLiteDatabase db = getReadableDatabase();
        ArrayList<String> list = new ArrayList<>();
        Cursor res = db.rawQuery(
            "SELECT (id || ' : ' || name || ' : ' || CAST(salary AS INT) || ' : ' || " +
            "strftime('%d-%m-%Y %H:%M:%S', datetime)) AS fullname FROM " + TABLE_NAME, null);

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

    boolean update(String name, String salary) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("salary", salary);
        db.update(TABLE_NAME, values, "name=?", new String[]{name});
        return true;
    }

    boolean delete() {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(TABLE_NAME, null, null);
        return true;
    }
}

Kết quả chạy ứng dụng

Khi nhập lương dạng số thực (ví dụ: 1500.75), nhấn nút Làm mới sẽ hiển thị danh sách với lương đã được chuyển thành số nguyên (1500) nhờ hàm CAST(salary AS INT).

Lưu ý quan trọng

  • Sử dụng ContentValues và phương thức insert()/update() an toàn hơn nối chuỗi SQL trực tiếp.
  • Luôn đóng Cursor sau khi dùng để tránh rò rỉ bộ nhớ.
  • Hàm CAST() hữu ích khi cần định dạng hiển thị khác kiểu lưu trữ.