Внедрение зависимости модели представления с помощью кинжала 2

У меня проблемы с внедрением зависимости в мою модель представления. Я продолжаю получать Невозможно создать экземпляр класса ....viewModel.UserProfileViewModel. Я пытался разобраться в этом вопросе. Любые предложения будут действительно оценены. Вот мой код. В других вопросах я видел, что это обычно вызвано наличием параметра в конструкторе модели представления, и создание фабрики должно решить проблему. но, похоже, это не сработало для меня. Я должен что-то упустить.

Спасибо!

 App component:

@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, ViewModelModule.class})
public interface ApplicationComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance Builder application(Application application);
        ApplicationComponent build();
    }
}
=====================================================
App module:

@Module
public class AppModule {
    Application mApplication;


    public AppModule(Application application){
        mApplication = application;
    }


    @Provides
    @Singleton
    Application providesApplication(){
        return mApplication;
    }
}

===========================================================
ViewFactory

@Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {

    private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

    @Inject
    public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> viewModels) {
        this.creators = viewModels;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        Provider<? extends ViewModel> creator = creators.get(modelClass);

        if (creator == null) {
            for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
                if (modelClass.isAssignableFrom(entry.getKey())) {
                    creator = entry.getValue();
                    break;
                }
            }
        }
        if (creator == null) {
            throw new IllegalArgumentException("unknown model class " + modelClass);
        }
        try {
            return (T) creator.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

===========================================================
View key

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelKey {
    Class<? extends ViewModel> value();
}

========================================================
View Module

@Module
public abstract class ViewModelModule {

    @Binds
    @IntoMap
    @ViewModelKey(UserProfileViewModel.class)
    abstract ViewModel bindUserViewModel(UserProfileViewModel userViewModel);
}

===========================================================
view model class

public class UserProfileViewModel extends ViewModel {

    private UserRepository mUserRepository;
    private LiveData<User> mObservableUser;

    @Inject
    public UserProfileViewModel(@NonNull UserRepository userRepo){
        this.mUserRepository = userRepo;
    }


    public void init(String userId){
        if (this.mObservableUser != null) {
            return;
        }
        mObservableUser = mUserRepository.getUser(userId);
    }

    public LiveData<User> getUser() {
        return this.mObservableUser;
    }

}

 ====================================================
in fragment

 viewModel = ViewModelProviders.of(this, viewModelFactory).get(UserProfileViewModel.class);
        viewModel.init(mUserId);

Откуда должен взяться

 App component:

@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, ViewModelModule.class})
public interface ApplicationComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance Builder application(Application application);
        ApplicationComponent build();
    }
}
=====================================================
App module:

@Module
public class AppModule {
    Application mApplication;


    public AppModule(Application application){
        mApplication = application;
    }


    @Provides
    @Singleton
    Application providesApplication(){
        return mApplication;
    }
}

===========================================================
ViewFactory

@Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {

    private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

    @Inject
    public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> viewModels) {
        this.creators = viewModels;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        Provider<? extends ViewModel> creator = creators.get(modelClass);

        if (creator == null) {
            for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
                if (modelClass.isAssignableFrom(entry.getKey())) {
                    creator = entry.getValue();
                    break;
                }
            }
        }
        if (creator == null) {
            throw new IllegalArgumentException("unknown model class " + modelClass);
        }
        try {
            return (T) creator.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

===========================================================
View key

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelKey {
    Class<? extends ViewModel> value();
}

========================================================
View Module

@Module
public abstract class ViewModelModule {

    @Binds
    @IntoMap
    @ViewModelKey(UserProfileViewModel.class)
    abstract ViewModel bindUserViewModel(UserProfileViewModel userViewModel);
}

===========================================================
view model class

public class UserProfileViewModel extends ViewModel {

    private UserRepository mUserRepository;
    private LiveData<User> mObservableUser;

    @Inject
    public UserProfileViewModel(@NonNull UserRepository userRepo){
        this.mUserRepository = userRepo;
    }


    public void init(String userId){
        if (this.mObservableUser != null) {
            return;
        }
        mObservableUser = mUserRepository.getUser(userId);
    }

    public LiveData<User> getUser() {
        return this.mObservableUser;
    }

}

 ====================================================
in fragment

 viewModel = ViewModelProviders.of(this, viewModelFactory).get(UserProfileViewModel.class);
        viewModel.init(mUserId);
?


person user642206    schedule 30.06.2018    source источник
comment
UserRepository должен быть внедрен Dagger во время выполнения, поэтому в приложении есть только один его экземпляр.   -  person EpicPandaForce    schedule 30.06.2018
comment
хорошо, но я не могу проверить ни это, ни точную ошибку, которую вы получаете: D   -  person user642206    schedule 30.06.2018
comment
Я видел людей с похожими проблемами, такими как конструктор с нулевым аргументом"> stackoverflow.com/questions/44194579/. Я следовал за ответом, но мне все еще кажется, что я что-то упускаю   -  person EpicPandaForce    schedule 30.06.2018
comment
Покажите полную трассировку стека.   -  person user642206    schedule 30.06.2018
comment
Трассировка стека 22:08:49.677 19211-19211/nonso.android.nonso E/AndroidRuntime: НЕИСПРАВНОЕ ИСКЛЮЧЕНИЕ: основной процесс: nonso.android.nonso, PID: 19211 java.lang.RuntimeException: невозможно создать экземпляр класса nonso.android .nonso.viewModel.UserProfileViewModel в android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:153) в android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) в android.arch.lifecycle .ViewModelProvider.get(ViewModelProvider.java:134) в android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) в nonso.android.nonso.ui.fragments.ProfileFragment.setUp(ProfileFragment.java:133) в nonso.android.nonso.ui.fragments.ProfileFragment.onActivityCreated(ProfileFragment.java:122) в android.support.v4.app.Fragment.performActivityCreated(Fragment.java:2355) в android.support.v4.app.FragmentManagerImpl. moveToState (фрагменты tManager.java:1451) в android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759) в android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827) в android.support.v4 .app.BackStackRecord.executeOps(BackStackRecord.java:797) в android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596) в android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383) ) в android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338) в android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245) в android.support.v4.app.FragmentManagerImpl$1 .run(FragmentManager.java:703) в android.os.Handler.handleCallback(Handler.java:790) в android.os.Handler.dispatchMessage(Handler.java:99) в android.os.Looper.loop(Looper. java:164) на андроиде. app.ActivityThread.main(ActivityThread.java:6494) в java.lang.reflect.Method.invoke(собственный метод) в com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) в com. android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Вызвано: java.lang.InstantiationException: java.lang.Class не имеет конструктора с нулевым аргументом в java.lang.Class.newInstance(собственный метод) в android. arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:151) в android.arch.lifecycle. ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) на android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) на android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) на nonso.android .nonso.ui.fragments.ProfileFragment.setUp(ProfileFragment.java:133) на nonso.android.nonso.ui.fragments.ProfileFragment.onActivityCreated(ProfileFragment.java:122) на android.support.v4.app.Fragment.performActivityCreated (Fragment.java:2355) на android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1451) на android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759) на android.support. v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827) на android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797) на android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager. java:2596) на android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383) на android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338) на android.support.v4.app .FragmentManagerImpl.execPendingActions(FragmentManager.java:2245) на android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703) на android.os.Handler.handleCallback(Handler.java:790) на android.os .Handler.dispatchMessage(Handler.java:99) на android.os.Looper.loop(Looper.java:164) на android.app.ActivityThread.main(ActivityThread.java:6494) на java.lang.reflect.Method. invoke(собственный метод) на com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) на com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)   -  person AutonomousApps    schedule 02.07.2018