使用匕首2注入viewmodel依赖项

时间:2018-06-30 19:09:16

标签: android mvvm dagger-2 android-viewmodel android-mvvm

在将依赖项注入到viewModel中时遇到问题。我不断收到无法创建类.... viewModel.UserProfileViewModel的实例。我一直试图找出这个问题。任何建议将不胜感激。这是我的代码。在其他问题中,我看到这通常是由于在viewmodel的构造函数中有一个参数引起的,创建工厂可以解决该问题。但是对于我来说,效果似乎不太好。我肯定错过了什么。

谢谢!

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

堆栈跟踪22:08:49.677 19211-19211 / nonso.android.nonso E / AndroidRuntime:FATAL EXCEPTION:main     进程: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(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)      原因: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)

0 个答案:

没有答案