我有一个应用程序,用户可以通过DialogFragment创建/删除/编辑列表。以前,在我的DialogFragments中有这样一个方法:
因此,我选择将所有CRUD方法放在一个单例类中,并像下面这样调用这些方法:
这是我创建的单例类,它现在包含了我的CRUD方法,而不是像以前一样将它们放在recyclerView的适配器类中。
MainActivtity.adapter.add(String name, String location, double price);
adapter
是我用于recyclerView的适配器对象。适配器类中包含了recyclerView中项目的创建/删除/编辑方法。如上所示的调用方式非常糟糕。因此,我选择将所有CRUD方法放在一个单例类中,并像下面这样调用这些方法:
Service.getInstance().add(...);
这是一种正确的方法吗?我还能做得更好吗?这是我创建的单例类,它现在包含了我的CRUD方法,而不是像以前一样将它们放在recyclerView的适配器类中。
public class Service {
private static Realm realm;
private static Service service = new Service();
private Service() {
realm = Realm.getInstance(App.getAppContex());
}
public static Service getInstance(){
if(service == null){
service = new Service();
}
return service;
}
public void add(String name, String location, double price) {
ShopListItem shopListItem = new ShopListItem();
shopListItem.setName(name);
shopListItem.setLocation(location);
shopListItem.setPrice(price);
shopListItem.setTimestamp(System.currentTimeMillis());
shopListItem.setIsBought(0);
realm.beginTransaction();
realm.copyToRealm(shopListItem);
realm.commitTransaction();
}
public void removeItem(int position, List<ShopListItem> shopListItems) {
realm.beginTransaction();
shopListItems.remove(position);
realm.commitTransaction();
}
这个类仅用于获取全局/应用程序上下文
public class App extends Application {
public static Application sApplication;
public static Application getsApplication(){
return sApplication;
}
public static Context getAppContex(){
return getsApplication();
}
@Override
public void onCreate() {
super.onCreate();
sApplication = this;
}
}
从这里开始更新问题:
以下是根据评论提出的建议采用的新方法: 现在,每次我想要在 Realm 数据库中执行 CRUD 操作时,我总是从我的 realm 对象中获取 getDefaultInstance 并以 realm.close() 结束;这个过程在每个 CRUD 方法中都会重复。
public class Service {
private Realm realm;
private static Service service = new Service();
private Service() {
}
public static Service getInstance(){
if(service == null){
service = new Service();
}
return service;
}
public void removeItem(int position, List<ShopListItem> shopListItems) {
//new: realm = Realm.getDefaultInstance();
realm = Realm.getDefaultInstance();
realm.beginTransaction();
shopListItems.remove(position);
realm.commitTransaction();
realm.close();
//new: realm.close();
}
按照 Realm 的建议,Realm 配置现在已经移至我的 Application 类中。
public class App extends Application {
public static Application sApplication;
public static Application getsApplication(){
return sApplication;
}
public static Context getAppContex(){
return getsApplication();
}
@Override
public void onCreate() {
super.onCreate();
sApplication = this;
final RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(App.getAppContex()).build();
realm.setDefaultConfiguration(realmConfiguration);
}
}
Realm
作为数据成员,它也不应该是静态成员。将其作为局部变量,这样就可以保证线程安全了。 - user207421