12

我想实现Repository模块来处理数据操作。我在row目录中有 JSON 文件,并希望创建具体Repository的实现来从文件中获取数据。我不确定是否可以ContextRepository.

例如

public class UserRepository {

    UserRepository() {}

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

2 回答 2

3

恕我直言,您应该使用像Dagger2这样的DI(依赖注入)来为您提供Context类似的东西,

应用模块类

@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);
    }
}

快乐编码..!!

于 2017-08-23T13:44:08.580 回答
1

我认为将上下文作为属性传递没有任何害处。如果您不喜欢这个想法,那么您可以通过一种方便的方法检索上下文:Static way to get 'Context' on Android?

于 2017-08-23T13:27:25.320 回答