2017-08-23 54 views
1

我想实现Repository模块来处理数据操作。我在row目录中有JSON文件,并且想要创建具体的Repository实现从文件中获取数据。我不确定我是否可以在构造函数或方法Repository中使用Context作为属性。存储库模块实现与上下文

例如

public class UserRepository { 

    UserRepository() {} 

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

你想用上下文来做什么?您将不需要它来访问文件系统... –

+0

我需要上下文来访问资源。正如我所提到的,我的原始目录中有我的json文件。 – Martin

+1

您可以将上下文作为参数传递,没有问题。 – finki

回答

1

恕我直言,你应该使用DI(依赖注入)像Dagger2,为您提供Context类似,

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

编码愉快.. !!