我在我的android项目中使用Realm。目前,我在应用程序类中定义了默认的领域配置,如下所示:
@Override
public void onCreate(){
super.onCreate();
myApplication=this;
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).deleteRealmIfMigrationNeeded().build();
Realm.setDefaultConfiguration(realmConfiguration);
Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler());
}在当前场景中,只有1个用户使用设备。她使用自己的凭据登录到应用程序,并使用默认的领域配置。
然而,随着新的需求,相同的android设备可以被不同的用户使用,因此我需要为每个用户配置不同的领域,以便每个用户都有自己的领域文件,对吧?
如果这是真的,那么管理领域配置的最佳方式是什么?我应该在我的登录活动中这样做吗?然后,我是否应该在登录活动中为每个用户创建不同的领域配置?
谢谢
Apurva
发布于 2016-07-19 18:21:39
由于您正在管理多个领域实例,因此使用工厂类将非常有用。可能看起来像这样,
public class RealmFactory {
/* Realm
* CAUTION: Be careful which thread you call this from, it is not Thread safe */
public static Realm getRealmInstance(Context context, String primaryKeyFromUser) {
return Realm.getInstance(getRealmConfiguration(context, primaryKeyFromUser));
}
/* RealmConfiguration */
private static RealmConfiguration getRealmConfiguration(Context context, String primaryKeyFromUser) {
return new RealmConfiguration.Builder(context)
.name(primaryKeyFromUser)
.encryptionKey(getSecurityKey())
.deleteRealmIfMigrationNeeded()
.build();
}
/* SecurityKey,
* CAUTION: This is just a sample */
private static byte[] getSecurityKey() {
char[] chars = "16CharacterLongPasswordKey4Realm".toCharArray();
byte[] key = new byte[chars.length * 2];
for (int i = 0; i < chars.length; i++) {
key[i * 2] = (byte) (chars[i] >> 8);
key[i * 2 + 1] = (byte) chars[i];
}
return key;
}
/* Check for Realm file */
public static boolean isRealmFileExists(Context context, String primaryKeyFromUser) {
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context)
.name(primaryKeyFromUser)
.encryptionKey(getSecurityKey())
.deleteRealmIfMigrationNeeded()
.build();
File realmFile = new File(realmConfiguration.getPath());
return realmFile.exists();
}
/* Delete Realm file, if exists
* CAUTION: if the Realm instance with given configuration is open, make sure you close it
* first, before deleting it, else an Exception will be thrown. */
public static void deleteRealmFile(Context context, String primaryKeyFromUser) {
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context)
.name(primaryKeyFromUser)
.build();
Realm.deleteRealm(realmConfiguration);
}
/* Delete all Realm files, if exists
* CAUTION: if the Realm instance with given configuration is open, make sure you close it
* first, before deleting it, else an Exception will be thrown. */
public static void deleteAllRealmFiles(Context context) {
File file = new File(context.getFilesDir().getPath());
File list[] = file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
for (File deleteFile : list) {
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context)
.name(deleteFile.getName())
.build();
Realm.deleteRealm(realmConfiguration);
}
}
}https://stackoverflow.com/questions/38443688
复制相似问题