从Sqlite迁移到Realm(Android)

我现有的应用数据在SQlite上.我正在尝试将数据从Sqlite迁移到Realm.我谷歌如何迁移数据,但没有找到任何与此相关的解决方案.

我计划推出现有应用的更新版本.在更新应用程序时,数据必须迁移到Realm,并且必须删除现有的Sqlite数据库.如果可能,请与解决方案分享一些想法.

解决方法:

假设您在DataBase(SqlLite)中存储了TODO列表,并且您希望将其迁移到realm DB.

TODO Item表的SqlLite接口

  interface TodoItemModel {
     String CREATE_TABLE = ""
            + "CREATE TABLE todo_list(\n"
            + "    _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n"
            + "    name TEXT NOT NULL,\n"
            + ")";
    String TABLE_NAME = "todo_item";

    //columns
    String _ID = "_id";
    String NAME = "name";
}

待办事项的领域对象

 public class TodoItem extends RealmObject {

    @PrimaryKey
    private Long _id;
    private String name;

    public TodoItem() {
    }

    public TodoItem(long id, String name) {
        this._id = id;
        this.name = name;
    }
}

步骤1.增加扩展SQLiteOpenHelper的DB的版本(即:下面给出的DbOpenHelper类).

步骤2.在使用onUpgrade函数的DbOpenHelper类中,您可以检查版本并将所有SqlLite数据记录存储到域db.

   final class DbOpenHelper extends SQLiteOpenHelper {

    //private static final int PREVIOUS_VERSION = 1;
    private static final int CURRENT_VERSION = 2;

    public DbOpenHelper(Context context) {
        super(context, "todo.db", null /* factory */, CURRENT_VERSION);
    }


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


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

        if (oldVersion < CURRENT_VERSION) {
            //get all the stored data in your db
            List<TodoItem> list = select_all_items_for_list(db);

            //open the realm transaction and store the list of todo's
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            realm.insertOrUpdate(list);
            realm.commitTransaction();
            //finally drop table
            db.execSQL("DROP TABLE IF EXISTS " + TodoItemModel.TABLE_NAME);
        }
    }

    private List<TodoItem> select_all_items_for_list(SQLiteDatabase db) {
        List<TodoItem> list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from " + TodoItemModel.TABLE_NAME, new String[0]);

        if (cursor == null)
            return list;

        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            final TodoItem todoItem = new TodoItem(cursor.getLong(cursor.getColumnIndex(TodoItemModel._ID)), cursor.getString(cursor.getColumnIndex(TodoItemModel.NAME));
            list.add(todoItem);
        }
        cursor.close();

        return list;
    }
}
上一篇:Realm Android javassist.NotFoundException:io.realm.com_example_realmtest_data_SomethingRealmProxyInt


下一篇:android – 我们可以免费使用Realm数据库,就像Sqlite和CoreData的替代品一样吗?