问题在于我尝试使用Dagger 2进行字段注入,但在运行时字段,应注入,始终为null
。我也尝试使用MVVM模式。这是我的代码:
ProfileActivity.java:
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "ProfileActivity: onStart: ");
final ProfileViewModel profileViewModel
= ViewModelProviders.of(this).get(ProfileViewModel.class);
profileViewModel.init();
profileViewModel.getUser().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User user) {
if (user != null) {
Log.d(TAG, "ProfileActivity: onStart: " + user.toString());
} else {
Log.d(TAG, "ProfileActivity: onStart: user == null");
}
}
});
}
ProfileViewModel.java:
public class ProfileViewModel extends ViewModel {
private LiveData<User> user;
@Inject
UserRepository userRepository;
public ProfileViewModel() {
Log.d(TAG, "ProfileViewModel: Constructor: ");
}
public void init() {
Log.d(TAG, "ProfileViewModel: init: ");
user = userRepository.getUser();
}
public LiveData<User> getUser() {
Log.d(TAG, "ProfileViewModel: getUser: ");
return user;
}
}
UserRepository.java:
@Singleton
public class UserRepository {
private LiveData<User> user;
@Inject
public UserRepository() {
Log.d(TAG, "UserRepository: Constructor: ");
}
public LiveData<User> getUser() {
Log.d(TAG, "UserRepository: getUser: ");
if (user != null) {
return user;
} else {
// There should be userDao.load() call,
// but it had been omitted for brevity.
MutableLiveData<User> user = new MutableLiveData<>();
user.setValue(DB.getUser());
return user;
}
}
}
MyApplication.java:
public class MyApplication extends MultiDexApplication implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
@Override
public void onCreate() {
super.onCreate();
DaggerMyApplicationComponent.create().inject(this);
}
@Override
public DispatchingAndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}
}
MyApplicationModule.java:
@Module
public abstract class MyApplicationModule {
@ContributesAndroidInjector
abstract ProfileActivity contributeActivityInjector();
}
MyApplicationComponent.java:
@Component(modules = { AndroidInjectionModule.class, MyApplicationModule.class})
@Singleton
public interface MyApplicationComponent extends AndroidInjector<MyApplication> {
void inject(ProfileActivity profileActivity);
}
在运行时,我可以看到下一个日志:
ProfileActivity: onStart:
ProfileViewModel: Constructor:
ProfileViewModel: init:
应用程序在user = userRepository.getUser();
ProfileViewModel
方法init()
内崩溃。
这意味着没有注射UserRepository
。此外,它还缺少UserRepository: Constructor:
日志。
我的错误在哪里?谢谢。
答案 0 :(得分:5)
基本上您需要做的是使用ViewModel Factory
将注入的UserRepository
传递到ViewModels
构造函数中,初始化它然后您就可以使用它了。您无法在ViewModels
中使用字段或参数注入。
我建议你关注这篇文章:Add the new ViewModel to your MVVM
它提供了足够的信息来开始将Dagger 2与架构组件一起使用。
希望它有所帮助。