I have HomeActivity
activity with bottom navigation bar and 5 fragments in it. I want to use RoomDatabase
in all of this fragments. How can I implement it?
HomeActivity code:
public class HomeActivity extends AppCompatActivity {
TextView tvDailyGoalValue;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
//layout setting
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationView navView = findViewById(R.id.nav_view);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_profile, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.fragment3);
NavigationUI.setupWithNavController(navView, navController);
sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
RoomDB roomDB = Room.databaseBuilder(this, RoomDB.class,"dripDB").build();
}
}
You should make a single, globally accessible instance of your RoomDB object. The Room docs even say so:
If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.
There are multiple ways you can share a single object across multiple Activities and Fragments, for example:
@Singleton
that you can @Inject
in all the relevant Activities and Fragments. Setting up Dagger is somewhat complicated if you're doing it for the first time, but this is the usual choice in professional apps.RoomDB
to a Singleton.Application
subclass, put the RoomDB
instance there and expose it to any Context
, e.g. ((YourCustomApplication)context.getApplication()).getRoomDB()
I'd say your best bet is 1) for scalability or 2) for simplicity.