The kingdom version is the last jar compiled from the source (github). I am using an Android project to create a realm file from a json file.
In this project, everything looks good, and the world is in order. Here is the code:
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() {
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(REALM_DB_FILE)
.setModules(new CurrencyModule())
.build();
Realm realm = Realm.getInstance(realmConfiguration);
File exportRealmFile = null;
try {
exportRealmFile = new File(getExternalCacheDir(), REALM_DB_FILE);
exportRealmFile.delete();
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
realm.close();
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);
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);
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) {
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) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
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 {
}
}
In my other project, I add category.realm to the raw folder and then copy it to the regular folder:
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);
}
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");
}
}
}
}
I get a failure when trying to get a database instance, and I get a message:
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)
I have no idea how to fix this. Any ideas? Thks
EDIT: I can open the generated file in real time using a Mac, and it seems perfect.
EDIT 2: Here is the missing method:
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) {
}
}