在项目中使用Android创建的Realm文件在另一个

时间:2015-06-08 17:24:22

标签: android realm

领域版本是我从源代码编译的最新jar(github)。 我正在使用Android项目从json文件创建域文件。

在这个项目中,一切似乎都很好,而且境界很好。这是代码:

public class MainActivity extends Activity {

private static final String REALM_DB_FILE = "categories.realm";
private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
            .name(REALM_DB_FILE)
            .setModules(new CurrencyModule())
            .build();
    Realm realm = Realm.getInstance(realmConfiguration);
    RealmResults<RLMCategory> r = realm.where(RLMCategory.class).findAll();
    if(r != null && r.size()> 0){
        Log.d(TAG, "items : "+r.size());
        realm.beginTransaction();
        r.clear();
        realm.commitTransaction();
        Log.d(TAG, "items : " + r.size());
    }
    String json = getJsonStringFromRawFile(this, R.raw.categories);
    try {
        JSONObject obj = new JSONObject(json);
        JSONArray arr =  obj.getJSONArray("results");
        for(int i = 0; i<arr.length(); i++){
            realm.beginTransaction();
            RLMCategory category = createFromJson((JSONObject) arr.get(i), i);
            RLMCategory categoryRLM = realm.copyToRealm(category);
            realm.commitTransaction();
        }
    } catch (JSONException e) {
        Log.e(TAG, "onCreate");
    }


    String path = realm.getPath();
    Log.d(TAG, "insert finished : path "+path);

    r = realm.where(RLMCategory.class).findAll();
    Log.d(TAG, "items : "+r.size());
    for (RLMCategory category : r){
        Log.d(TAG, toString(category));
    }
    realm.close();

    sendDatabaseByEmail();
}

public void sendDatabaseByEmail() {

      // init realm
//        Realm realm = Realm.getInstance(this);
    RealmConfiguration realmConfiguration = new    RealmConfiguration.Builder(this)
            .name(REALM_DB_FILE)
            .setModules(new CurrencyModule())
            .build();
    Realm realm = Realm.getInstance(realmConfiguration);

    File exportRealmFile = null;
    try {
        // get or create an "export.realm" file
        exportRealmFile = new File(getExternalCacheDir(), REALM_DB_FILE);

        // if "export.realm" already exists, delete
        exportRealmFile.delete();

        // copy current realm to "export.realm"
        realm.writeCopyTo(exportRealmFile);

    } catch (IOException e) {
        e.printStackTrace();
    }
    realm.close();

    // init email intent and add export.realm as attachment
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("plain/text");
    intent.putExtra(Intent.EXTRA_EMAIL, "valeria@letgo.com");
    intent.putExtra(Intent.EXTRA_SUBJECT, REALM_DB_FILE +" database");
    intent.putExtra(Intent.EXTRA_TEXT, "datatabse");
    Uri u = Uri.fromFile(exportRealmFile);
    intent.putExtra(Intent.EXTRA_STREAM, u);

    // start email intent
    startActivity(Intent.createChooser(intent, "Send database"));
}

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

public String toString(RLMCategory rlmCategory) {
    return "RLMCategory{" +
            "id=" + rlmCategory.getId() +
            ", name='" + rlmCategory.getName() + '\'' +
            ", description='" + rlmCategory.getDescription() + '\'' +
            ", image_src='" + rlmCategory.getImage_src() + '\'' +
            ", category_id=" + rlmCategory.getCategory_id() +
            ", name_dirify='" + rlmCategory.getName_dirify() + '\'' +
            ", objectId='" + rlmCategory.getObjectId() + '\'' +
            '}';
}


@Nullable
public static String getJsonStringFromRawFile(Context context, int resId) {
    InputStream is = context.getResources().openRawResource(resId);
    return getJsonStringFromIS(is);
}

private static String getJsonStringFromIS(InputStream inputStream){
    String jsonStr = null;
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = null;
    if (inputStream == null) {
        // Nothing to do.
        jsonStr = null;
    } else {
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }
            if (buffer.length() == 0) {
                jsonStr =  null;
            } else {
                jsonStr = buffer.toString();
            }
        } catch (IOException e) {
            Log.e(TAG, "getJsonStringFromIS", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }
    return jsonStr;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public static RLMCategory createFromJson(JSONObject obj, int id){
    RLMCategory category = null;
    try {
        category = new RLMCategory();
        category.setName(obj.getString("name"));
        category.setId(id);
        category.setCategory_id(obj.getInt("category_id"));
        category.setDescription(obj.getString("description"));
        category.setName_dirify(obj.getString("name_dirify"));
        category.setImage_src(obj.getString("image"));
        category.setObjectId(obj.getString("description"));
    } catch (JSONException e) {
        Log.e(TAG, "createFromJson : " +obj, e );
    }
    return category;
}

@RealmModule(classes = {RLMCategory.class})
public class CurrencyModule {

}

}

在我的另一个项目中,我将categories.realm添加到raw文件夹,然后将其复制到普通文件夹:

Utils.copyRealmDb(context, REALM_DB_FILE, CATEGORIES_RES);
RealmConfiguration realmConfiguration2 = new    RealmConfiguration.Builder(context)
            .name(REALM_DB_FILE)
            .setModules(new CategoryModule())
            .build();

    this.realm = Realm.getInstance(realmConfiguration2); //crash here
}

public static void copyRealmDb(Context context, String realmDbFile, @RawRes int rarResFile) {
    File f = context.getFilesDir();
    File targetFile = new File(f, realmDbFile);
    if(targetFile.exists()){
        targetFile.delete();
    }
    if(!targetFile.exists()){
        InputStream is = context.getResources().openRawResource(rarResFile);
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(targetFile);
            copyStream(is, os);
        } catch (FileNotFoundException e) {
            Timber.e(e, "Unable to copy database from raw");
        } finally {
            try {
                if(is != null){
                    is.close();
                }
            } catch (IOException e) {
                Timber.e(e, "Unable to close inputStream");
            }
            try {
                if(os != null){
                    os.close();
                }
            } catch (IOException e) {
                Timber.e(e, "Unable to close outputStream");
            }
        }
    }
}

我在尝试获取数据库实例时遇到了崩溃,我得到的错误是:

Caused by: java.lang.IllegalArgumentException: Illegal Argument: Invalid format of Realm file.
        at io.realm.internal.SharedGroup.createNativeWithImplicitTransactions(Native Method)
        at io.realm.internal.SharedGroup.<init>(SharedGroup.java:60)
        at io.realm.Realm.<init>(Realm.java:189)
        at io.realm.Realm.createAndValidate(Realm.java:557)
        at io.realm.Realm.create(Realm.java:525)
        at io.realm.Realm.getInstance(Realm.java:498)

我不知道如何修复它。有任何想法吗? THKS

编辑:我可以用Mac打开创建的领域文件,看起来很好。

编辑2:这是缺少的方法:

public static void copyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (;;) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {
    }
}

0 个答案:

没有答案