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

Cách truy vấn dữ liệu trong giờ vừa qua trong Android SQLite

Giới thiệu

SQLite là cơ sở dữ liệu nhẹ tích hợp sẵn trong Android, không cần kết nối phức tạp. Bài viết này minh họa cách lọc bản ghi có timestamp nằm trong 1 giờ gần nhất.

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

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

File → New Project → điền thông tin → Finish.

Bước 2: Giao diện (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"/>
</LinearLayout>

Nhấn "Làm mới" để tải dữ liệu trong 1 giờ qua.

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;
    ListView listView;

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

        final DatabaseHelper helper = new DatabaseHelper(this);
        final ArrayList array_list = helper.getAllContacts();

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

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

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

        findViewById(R.id.update).setOnClickListener(v -> {
            if (validateInput()) {
                Toast.makeText(this, helper.update(name.getText().toString(), salary.getText().toString()) ?
                        "Đã cập nhật" : "Cập nhật thất bại", Toast.LENGTH_LONG).show();
            }
        });

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

        findViewById(R.id.save).setOnClickListener(v -> {
            if (validateInput()) {
                Toast.makeText(this, helper.insert(name.getText().toString(), salary.getText().toString()) ?
                        "Đã thêm" : "Thêm thất bại", Toast.LENGTH_LONG).show();
            }
        });
    }

    private boolean validateInput() {
        if (name.getText().toString().isEmpty() || salary.getText().toString().isEmpty()) {
            name.setError("Nhập tên");
            salary.setError("Nhập lương");
            return false;
        }
        return true;
    }
}

Bước 4: DatabaseHelper.java - Truy vấn 1 giờ qua

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 {
    static final String DATABASE_NAME = "salaryDatabase5";
    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 TEXT, datetime DEFAULT CURRENT_TIMESTAMP)");
    }

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

    boolean insert(String n, String s) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("name", n); cv.put("salary", s);
        db.replace(TABLE_NAME, null, cv);
        return true;
    }

    ArrayList getAllContacts() {
        SQLiteDatabase db = getReadableDatabase();
        ArrayList list = new ArrayList<>();

        // Truy vấn bản ghi trong 1 giờ gần nhất
        Cursor res = db.rawQuery(
            "SELECT (id || ' : ' || name || ' : ' || salary || ' : ' || datetime) AS fullname " +
            "FROM " + TABLE_NAME + " WHERE datetime >= datetime('now', '-1 hour')", null);

        while (res.moveToNext()) {
            list.add(res.getString(res.getColumnIndex("fullname")));
        }
        return list;
    }

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

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

Giải thích truy vấn

Hàm datetime('now', '-1 hour') trả về thời điểm đúng 1 giờ trước thời điểm hiện tại. Điều kiện WHERE datetime >= ... sẽ chỉ lấy các bản ghi được tạo trong khung giờ đó.

Kết quả

Cách truy vấn dữ liệu trong giờ vừa qua trong Android SQLite

Màn hình hiển thị các bản ghi được chèn trong giờ vừa qua.