我正在使用Realm和我的android项目。目前我在我的应用程序类中定义默认域配置,如下所示 -
@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
答案 0 :(得分:1)
IMO,使用工厂类会很有用,因为您正在管理多个Realm实例。可能看起来像这样,
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);
}
}
}