how to properly pass context between methods to use database repository? how to properly pass context between methods to use database repository? sqlite sqlite

how to properly pass context between methods to use database repository?


You always need a Context to access the SQLite database so what u could do is change the constructor of that specific tool class and pass a new instance of PlayerRepository as a parameter. This prevents your tool class of needing a context itself.

Imo if u have multiple classes using the database best approach is to create a new class whose only job is doing database actions and put all the needed action inside that one.

Just create an object of this database class with the Context of the current activity the to Tools and PlayerRepository constructors. This way neither your PlayerRepository or Tools classes need Context and both can make actions on the database.Even if you should really need Context in PlayerRepository it is always best to keep all database related functions centralized in a single class.


I understand that this is an old question but still i'll write for those like me who will pass by this in future.

In order to get rid of the context problem with repository pattern used for accessing database you can implement DI (Dependency Injection) pattern in your project. There are many reasons to do such and that question illustrates one of them.

If you implement DI you would have only one instance of database repository amongst the entire module (or app). This instance would be created in a class which has context, and injected to those classes where needed.One of the simpliest approaches for using DI is to use Dagger 2 library. All of the related information you could find on their site.