I'm trying to implement Room database in my project, but i have a problem. I am using MVC pattern and in presenter, I want to initialize room database. But to do that, I need a context, which presenter should not have. What I am doing wrong?
My Room DB:
@Database(entities = {SportEvent.class},version = 1)
public abstract class RecommendedEventsDB extends RoomDatabase {
private static RecommendedEventsDB INSTANCE;
public abstract SportEventDao sportEventDao();
//singleton instance of database
public static RecommendedEventsDB getRecommendedEventsDB(Context context){
if(INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
RecommendedEventsDB.class, "recommended_Events")
.allowMainThreadQueries() //need to be deleted, for testing purpose only!!!
.build();
}
return INSTANCE;
}
}
And in Presenter i would like to initiate DB:
RecommendedEventsDB db = RecommendedEventsDB.getRecommendedEventsDB(context);
but i have not context...
Can you help me please?
There was a talk about Fragment
s (Google I/O 2016) according to which
Fragments are part of the ? in MV?
(at about 9:30 min.) And Fragment
s do have a Context
as long as they are attached to an Activity
.
An interesting point of view.
But if one insists on having an Android
-free Presenter, then one can use an interface
(or two):
A Presenter needs an interface
- let's call it ViewInterface
- to communicate with the Fragment
or Activity
or View
to which it belongs. Without this ViewInterface
, nothing can happen in the "real world".
The database (as a means of physically storing data and accessing stored data) is very much part of this "real world", so it is only fitting that the Presenter asks its ViewInterface
to make someone or something instantiate the data storage facility and please come back with another interface
so the Presenter can cause all the CRUD operations to happen. Let's call this one DatabaseInterface
.
So basically, you have two interface
s. The first one could be implemented by a Fragment
or View
interface ViewInterface{
// ...
DatabaseInterface getDatabaseInterface();
}
The second one can be implemented by another class which will then manage the database operations
interface DatabaseInterface{
void insertNewCustomer(Customer customer);
void deleteCustomer(long customerDbId);
List<Customer> findAllCustomers();
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.