在 android 中存储数据元组的代码量最少

Least amount of code to store data tuples in android

在 Android 中,shortest/easiest 仅存储连接值的简单元组 f.ex 的方法是什么? Date dateString nameint count?

使用 SharedPreferences,您可以保留递增 ID 并将值存储为

editor = context.getSharedPreferences().edit();
editor.putString("name" + ID, name);
editor.putLong("date" + ID, date.getTime());
editor.putInt("count" + ID, count);
editor.apply();
ID += 1;

但解决方案应扩展到数千个条目。这实际上是关于存储非常简单的数据,所以像 might be overkill. 这样的数据库似乎需要很多样板文件。

哪种方法需要的编程 effort/lines 代码最少?

更新:也许 Android Room 可行?

对于最简单的数据,您可以创建一个对象 class 并将您的值放入其中,然后使用 Gson, and save your JSON in SharedPreferences as a single value. then you can retrieve JSON from SharedPreferences and convert to your Object by using Gson 将您的 class 转换为 JSON。

将对象转换为 JSON:

String jsonString = new Gson().toJson(yourModel);

将 JSON 从字符串转换为对象:

YourObject myModel = new Gson().fromJson(jsonString, YourObject.class);

这是一个非常基本的 SQLiteOpenHelper 示例,它有一个 table 并且可以完成 select 所有并创建一行

public class DbHelper extends SQLiteOpenHelper {

    public static class Entry {
        public long id;
        public String value;
    }

    public static final int VERSION = 1;
    public static final String NAME = "MyDb";

    private static final String TABLE_ENTRY = "MyTable";
    private static final String KEY_ENTRY_ID = "id";
    private static final String KEY_ENTRY_VALUE = "value";

    private static final String SQL_CREATE_ENTRY_TABLE = "CREATE TABLE "+ TABLE_ENTRY + "(" +
            KEY_ENTRY_ID + " INTEGER PRIMARY KEY, " +
            KEY_ENTRY_VALUE + " TEXT" +
            ")";

    public DbHelper(Context context) {
        super(context, NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRY_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public List<Entry> selectAll(){
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ENTRY, null);
        List<Entry> output = new ArrayList<>();
        if(cursor.moveToFirst()){
            while(!cursor.isAfterLast()){
                Entry entry = new Entry();
                entry.id = cursor.getLong(cursor.getColumnIndex(KEY_ENTRY_ID));
                entry.value = cursor.getString(cursor.getColumnIndex(KEY_ENTRY_VALUE));
                output.add(entry);
                cursor.moveToNext();
            }
        }
        return output;
    }

    public long createEntry(Entry entry){
        SQLiteDatabase db = getWritableDatabase();

        try {
            ContentValues values = new ContentValues();
            values.put(KEY_ENTRY_VALUE, entry.value);

            return db.insert(TABLE_ENTRY, null, values);
        }catch (Exception e){
            return -1;
        }
    }
}

查看 JDXA ORM Android 以轻松将对象数据存储在 SQLite 数据库中。它可以帮助您避免编写如下所示的样板代码。免责声明:我是JDXA ORM的架构师。

JDXA 是非侵入式的、灵活的并且对 POJO 友好。在这种特殊情况下,您可以声明一个 POJO class SampleEntity,如下所示:

public class SampleEntity {
    private int id; // auto-generated by the database
    private String name;
    private Date date;
    private long count;

    /**
     * Default no-arg constructor needed for JDXA
     */
    public SampleEntity() {
    }

    public SampleEntity(String name, Date date, long count) {
        this.name = name;
        this.date = date;
        this.count = count;
    }

    // Other constructors and accessor methods omitted

此 class 的对象关系映射 (ORM) 规范可以声明式定义如下:

CLASS SampleEntity
    PRIMARY_KEY id
    SQLMAP FOR id SQLTYPE 'INTEGER PRIMARY KEY AUTOINCREMENT'
    RDBMS_GENERATED id
;

上面的RDBMS_GENERATED规范意味着指定属性(例如id)的值将由底层数据库自动生成。

JDXA 为 CRUD 操作提供了简单的 APIs。以下是此类 API 调用(例如,插入、查询、删除)的一些示例:

JDXS jdxHandle = jxResource.getJDXHandle();

String sampleEntityClassName = SampleEntity.class.getName();

try {           
    // Delete all existing SampleEntity objects from the database.
    jdxHandle.delete2(sampleEntityClassName, null, JDXS.FLAG_DEEP);

    // Create and save some SampleEntity objects. id will be automatically generated by the database.
    SampleEntity entity = new SampleEntity("Name1", new Date(), 10);
    jdxHandle.insert(entity, 0, null);

    entity = new SampleEntity("Name2", new Date(), 20);
    jdxHandle.insert(entity, 0, null);

    // Retrieve all the SampleEntity objects. They will come initialized with the database generated id values.
    List queryResults = jdxHandle.query(sampleEntityClassName, null, JDXS.ALL, JDXS.FLAG_DEEP, null); 
    ...
 } catch (Exception ex) {
 ...
 }

您不需要编写和维护任何 SQL 代码。此外,还避免了许多用于数据传输的样板代码。此外,JDXA 将自动生成所需的数据库模式。