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

Cách sử dụng kiểu smallint trong SQLite Android

Giới thiệu

SQLite Android hỗ trợ nhiều kiểu dữ liệu. Ví dụ này minh họa cách dùng kiểu SMALLINT cho cột lương (giá trị nguyên nhỏ).

Bước 1: Tạo project mới

Mở Android Studio, chọn File → New Project, điền thông tin.

Bước 2: 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="number"
        android:hint="Nhập lương (smallint)"
        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/udate" 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: 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.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    EditText name, salary;
    private ListView listView;
    ArrayList array_list;
    ArrayAdapter arrayAdapter;

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

        final DatabaseHelper helper = new DatabaseHelper(this);
        array_list = 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, array_list);
        listView.setAdapter(arrayAdapter);

        // Các nút bấm: Xóa, Cập nhật, Làm mới, Lưu - tương tự ví dụ trước
        findViewById(R.id.Delete).setOnClickListener(v -> {
            if (helper.delete()) Toast.makeText(this, "Đã xóa", Toast.LENGTH_LONG).show();
            else Toast.makeText(this, "Không xóa được", Toast.LENGTH_LONG).show();
        });

        findViewById(R.id.udate).setOnClickListener(v -> {
            if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
                if (helper.update(name.getText().toString(), salary.getText().toString()))
                    Toast.makeText(this, "Đã cập nhật", Toast.LENGTH_LONG).show();
                else Toast.makeText(this, "Không cập nhật được", Toast.LENGTH_LONG).show();
            } else {
                name.setError("Nhập tên"); salary.setError("Nhập lương");
            }
        });

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

        findViewById(R.id.save).setOnClickListener(v -> {
            if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
                if (helper.insert(name.getText().toString(), salary.getText().toString()))
                    Toast.makeText(this, "Đã thêm", Toast.LENGTH_LONG).show();
                else Toast.makeText(this, "Không thêm được", Toast.LENGTH_LONG).show();
            } else {
                name.setError("Nhập tên"); salary.setError("Nhập lương");
            }
        });
    }
}

Bước 4: DatabaseHelper.java - dùng SMALLINT

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.SQLiteOpenHelper;
import java.util.ArrayList;

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

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Sử dụng SMALLINT cho cột salary
        db.execSQL("CREATE TABLE " + TABLE_NAME +
                "(id INTEGER PRIMARY KEY, name TEXT, salary SMALLINT, datetime DEFAULT CURRENT_TIMESTAMP)");
    }

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

    public boolean insert(String name, String salary) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("salary", salary); // SQLite tự chuyển đổi
        db.replace(TABLE_NAME, null, cv);
        return true;
    }

    // Truy vấn hiển thị đầy đủ: id : name : salary : datetime
    public ArrayList getAllContacts() {
        SQLiteDatabase db = getReadableDatabase();
        ArrayList list = new ArrayList<>();
        Cursor res = db.rawQuery("SELECT id || ' : ' || name || ' : ' || salary || ' : ' || datetime AS fullname FROM " + TABLE_NAME, null);
        if (res.moveToFirst()) {
            do {
                list.add(res.getString(res.getColumnIndex("fullname")));
            } while (res.moveToNext());
        }
        res.close();
        return list;
    }

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

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

Chạy ứng dụng

Kết quả: danh sách hiển thị các cột id, tên, lương (smallint), thời gian. Nhấn "Làm mới" để cập nhật ListView.

Cách sử dụng kiểu smallint trong SQLite Android

Cách sử dụng kiểu smallint trong SQLite Android