如何在Android中正确使用预先填充的Realm数据库?

时间:2016-05-05 15:16:43

标签: android realm

我正在使用Realm 0.90.0并且我在加载预填充的Realm db时遇到问题:一旦我从源加载文件,返回的集合上的isEmpty给出了true,当它显然不是'(我是通过在Realm Browser中导入csv创建的,在那里打开数据库时一切都很好。)

这是我到目前为止所做的:

  • 我在我的res/raw文件夹

  • 中放置了一个域数据库文件
  • 我通过

    MyApplication课程中加载了它
    copyBundledRealmFile(this.getResources().openRawResource(R.raw.station), Realm.DEFAULT_REALM_NAME); // more info about this is said later
    RealmConfiguration config = new RealmConfiguration.Builder(this)
                    .deleteRealmIfMigrationNeeded()
                    .build();
    Realm.deleteRealm(config);
    Realm.setDefaultConfiguration(config);
    
  • 然后在我的片段中onViewCreated我查询了其中的每个对象

    Realm realm = Realm.getDefaultInstance();
    RealmResults<Station4Database> stations = realm.where(Station4Database.class).findAll();
    Log.d("TAG", "stations loading ended", 
          stations.isLoaded(),// true
          stations.isValid(), // true
          stations.isEmpty(), // true instead of FALSE
          stations.size());   // 0 instead of 2929 (actual size)
    

为什么不让对象正确?任何帮助/意见都会非常感激!

谢谢!

PS这是我从Realm的回购中的官方示例中获取的功能(应该使工作正确)。

private String copyBundledRealmFile(InputStream inputStream, String outFileName) {
    try {
        File file = new File(this.getFilesDir(), outFileName);
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, bytesRead);
        }
        outputStream.close();
        return file.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (java.io.IOException e) {
        e.printStackTrace();
    }
    return null;
}

1 个答案:

答案 0 :(得分:0)

终于解决了!

问题是我在数据库中使用模型类的非完美映射版本(Station4Database在这种特定情况下,字段名称不完全相同!)。< / p>

因此,请记住,如果您不想在Realm中检索空集合而不向您提供任何类型的错误/异常,请始终使用Realm Browser生成的模型定义。