从Sqlite迁移到Realm(Android)

时间:2017-01-04 05:11:33

标签: android sqlite realm realm-migration

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

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

1 个答案:

答案 0 :(得分:7)

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

TODO项目表的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";
}

ToDo项目的领域对象

 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 (即:下面给出的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;
    }
}