I have an app where the user can create/delete/edit to a list from a DialogFragment. Before I had a method like this in my DialogFragments: MainActivtity.adapter.add(String name, String location, double price);
adapter is my adapter object for the recyclerView. The class for the adapter had my create/delete/edit methods for the items in the recyclerView. Which was called like shown above which also is a horrible way to call mehtods as I understand.
So I choose to put all these CRUD methods in a one singleton class and call these method like this: Service.getInstance().add(...);
Is this a correct approach and what could I have done better?
This is how I made the singleton class that now contains my CRUD methods, instead of putting them in my adapter class for the recyclerView as before.
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();
}
This class is just used for getting the global/Application context
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;
}
}
Aucun commentaire:
Enregistrer un commentaire