我想将我的领域数据库复制到SD卡 为此,我使用此代码:
byte[] key=new byte[64];
new SecureRandom().nextBytes(key);
Realm realm = Realm.getInstance(App.realmConfiguration);
try {
realm.writeEncryptedCopyTo(new File(Environment.getExternalStorageDirectory(), "encryptRealm.txt"),key);
Toast.makeText(getApplicationContext(),"success saving",Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"error saving",Toast.LENGTH_LONG).show();
}
try {
realm.writeCopyTo(new File(Environment.getExternalStorageDirectory(),"simpleRealm.txt"));
Toast.makeText(getApplicationContext(),"success saving",Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"error saving",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
但是当我运行我的应用时,我收到此错误消息:
at io.realm.internal.Group.nativeWriteToFile(Native Method)
at io.realm.internal.Group.writeToFile(Group.java:226)
at io.realm.internal.SharedGroupManager.copyToFile(SharedGroupManager.java:141)
at io.realm.BaseRealm.writeEncryptedCopyTo(BaseRealm.java:254)
at io.realm.Realm.writeEncryptedCopyTo(Realm.java:122)
at com.medium.ir.test.MainActivity$2.onClick(MainActivity.java:73)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
但是当我将复制文件的文件位置更改为此
时realm.writeEncryptedCopyTo(new File(context.getFilesDir(), "new-name"), getNewKey());
我的应用程序崩溃但我无法获取我的领域数据库文件。" root access nedded"
顺便说一下,这个ligale是用sd卡复制realm数据库的吗?
谁能帮帮我呢?
答案 0 :(得分:0)
首先检查您的应用程序类在onCreateMethod()
中是否具有以下代码
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration.Builder configBuilder = new RealmConfiguration.Builder()
.name("yourDbName.realm")
.migration(migration)
.schemaVersion(REALM_DB_VERSION);//Your db version
Realm.setDefaultConfiguration(configBuilder.build());
}
现在,将此代码粘贴到要将数据导出到外部存储的位置。
final Realm realm = Realm.getDefaultInstance();
try {
final File file = new File(Environment.getExternalStorageDirectory().getPath().concat("/sample.realm"));
if (file.exists()) {
file.delete();
}
realm.writeCopyTo(file);
Toast.makeText(MyActivity.this, "Successful export to a realm file", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
realm.close();
e.printStackTrace();
}
仅此而已:)