12

I would like to implement Repository module to handle data operations. I have JSON file in row directory and want create concrete Repository implementation to get data from file. I'm not sure if I can use Context as attribute in the constructor or method of Repository.

e.g.

public class UserRepository {

    UserRepository() {}

    public List<User> loadUserFromFile(Context contex) {
        return parseResource(context, R.raw.users);
    }
}
Martin
  • 2,146
  • 4
  • 21
  • 32

2 Answers2

3

IMHO, you should use DI (Dependency Injection) like Dagger2, to provide you Context something like,

AppModule.class

@Module
public class AppModule {

    private Context context;

    public AppModule(@NonNull Context context) {
        this.context = context;
    }

    @Singleton
    @Provides
    @NonNull
    public Context provideContext(){
        return context;
    }

}

MyApplication.class

public class MyApplication extends Application {

    private static AppComponent appComponent;

    public static AppComponent getAppComponent() {
        return appComponent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = buildComponent();
    }

    public AppComponent buildComponent(){
        return DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }
}

UserRepository.class

@Singleton
public class UserRepository {

    UserRepository() {}

    @Inject
    public List<User> loadUserFromFile(Context contex) {
        return parseResource(context, R.raw.users);
    }
}

Happy Coding..!!

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
  • 4
    The context should be retrieved from the activity which instantiate the model, which owns the repository, but not statically; it should be retrieved [on demand](https://stackoverflow.com/a/38967293/4469112), that is it should be passed – Alessio Nov 16 '18 at 07:28
  • Agree! This completely defies the logic of keeping a low coupling. Best way is to inject the context while repository object is created. – sud007 Oct 20 '20 at 06:59
1

I don't see any harm in passing the context as an attribute. If you dislike the idea then you can retrieve the context via a convenient method : Static way to get 'Context' on Android?

Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
  • 2
    Please don't retrieve the context statically, retrieve it [on demand](https://stackoverflow.com/a/38967293/4469112) – Alessio Nov 16 '18 at 07:27