一:数据库工具类
package com.jwt.mysqltiledemo;import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONObject;public class DataStorageHelper extends SQLiteOpenHelper {private static final String DATABASE_NAME = "DataStorage.db";private static final int DATABASE_VERSION = 1;private static final String TABLE_NAME = "data_table";private static final String COLUMN_ID = "_id";private static final String COLUMN_DATA = "data";private static final String COLUMN_TIMESTAMP = "timestamp";public DataStorageHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ COLUMN_DATA + " TEXT,"+ COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" + ")";db.execSQL(CREATE_TABLE);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// Drop older table if existeddb.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);// Create tables againonCreate(db);}/*** 存储数据** @param data 要保存的数据,以JSON字符串形式*/public void save_data(String data) {SQLiteDatabase db = this.getWritableDatabase();try {JSONObject json = new JSONObject(data); // 验证是否为有效的JSONString insertQuery = "INSERT INTO " + TABLE_NAME + " (" + COLUMN_DATA + ") VALUES (?)";db.execSQL(insertQuery, new Object[]{data});} catch (Exception e) {Log.e("DataStorageHelper", "Error while saving data: " + e.getMessage());}}/*** 加载并删除最旧的数据** @return 最旧的数据项*/@SuppressLint("Range")public String load_data() {SQLiteDatabase db = this.getWritableDatabase();String oldestData = null;try (Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_DATA}, null, null, null, null, COLUMN_TIMESTAMP + " ASC", "1")) {if (cursor != null && cursor.moveToFirst()) {oldestData = cursor.getString(cursor.getColumnIndex(COLUMN_DATA));// 删除这条记录String deleteQuery = "DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_DATA + " = ?";db.execSQL(deleteQuery, new Object[]{oldestData});}} catch (Exception e) {Log.e("DataStorageHelper", "Error while loading and deleting data: " + e.getMessage(), e);} finally {// 确保数据库连接被关闭(虽然在这个例子中由框架管理)db.close();}return oldestData;}
}
二:使用
package com.jwt.mysqltiledemo;import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;public class MainActivity extends AppCompatActivity {private DataStorageHelper dataStorageHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dataStorageHelper = new DataStorageHelper(this);// 插入JSON数据JSONObject jsonObject = new JSONObject();try {jsonObject.put("_id", "1");jsonObject.put("data_table", "Alice");jsonObject.put("data", 25);jsonObject.put("timestamp", System.currentTimeMillis());} catch (Exception e) {e.printStackTrace();}// 存储数据storeData(jsonObject.toString());// 加载并删除最旧的数据String oldestData = loadAndDeleteOldestData();// 打印最旧的数据if (oldestData != null) {Log.d("======MainActivity", "Oldest Data: " + oldestData);} else {Log.d("======MainActivity", "No data to load");}}private void storeData(String data) {// 使用 DataStorageHelper 存储数据dataStorageHelper.save_data(data);Log.d("======MainActivity", "Data stored successfully");}private String loadAndDeleteOldestData() {// 使用 DataStorageHelper 加载并删除最旧的数据return dataStorageHelper.load_data();}
}