安卓实现一个记账本(SQLite存储数据)
以下是一个简单的记账本应用程序的示例代码,使用了SQLite数据库来存储记录。
首先,创建一个Account
类,用于表示账目信息:
public class Account {
public int id;
public String description;
public float amount;
public Account(String description, float amount) {
this.description = description;
this.amount = amount;
}
// 空构造器,用于ORM
public Account() {}
// Getter和Setter略...
}
然后,创建一个DatabaseHelper
类,用于管理数据库的创建和维护:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "account_db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "accounts";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "DESC TEXT,"
+ "AMOUNT REAL" + ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
最后,创建一个AccountManager
类,用于账目的增删改查操作:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class AccountManager {
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
public AccountManager(Context context) {
dbHelper = new DatabaseHelper(context);
}
public void addAccount(Account account) {
db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("DESC", account.description);
values.put("AMOUNT", account.amount);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
db.close();
}
public List<Account> getAllAccounts() {
List<Account> accounts = new ArrayList
评论已关闭