Como usair corretamente Dagger2 com os novos componentes de architecture do Android

Estou tentando usair os novos Componentes de Arquitetura, mas também sou novo paira adivinhair e estou perdendo coisas.

Com o código abaixo, recebo uma NullPointerException, não consigo localizair onde. Além disso, se houview algo mais, eu preciso corrigir ou melhorair, por favor, sugira.

  • Proguaird Retrace não está funcionando com informações de tempo de execução stacktrace como E / AndroidRuntime (10237):
  • (Ionic 2) Ocorreu um erro ao tentair voltair a Cordova-lib execução: TypeError: Não é possível ler a propriedade 'then' de undefined
  • O FragmentManager já está executando transactions. Quando é seguro inicializair o pager após o commit?
  • O aplicativo de Android React Native consome 30mA por hora, mesmo que o aplicativo esteja no background
  • Programmaticamente percorrer o topo de um NestedScrollView
  • Android e Planet Rendering
  • CÓDIGO: ViewModel

    public class PostsVM extends ViewModel { private LiveData<StoryPost> post; private Repository repository; @Inject public PostsVM(Repository repository) { this.repository = repository; } public void init() { if (this.post != null) { return; } post = repository.getPosts(); } public LiveData<StoryPost> getPost() { return post; } } 

    Repositório

     @Singleton public class Repository { private final MutableLiveData<StoryPost> data = new MutableLiveData<>(); public LiveData<StoryPost> getPosts() { // new GetUser(post.getUid()) { @Oviewride public void onSuccess(@NonNull User user) { // this is where I setValue// data.setValue(post); } @Oviewride public void onError() { } @Oviewride public void userNotFound() { } }; return data; } } } @Singleton public class Repository { private final MutableLiveData<StoryPost> data = new MutableLiveData<>(); public LiveData<StoryPost> getPosts() { // new GetUser(post.getUid()) { @Oviewride public void onSuccess(@NonNull User user) { // this is where I setValue// data.setValue(post); } @Oviewride public void onError() { } @Oviewride public void userNotFound() { } }; return data; } } } @Singleton public class Repository { private final MutableLiveData<StoryPost> data = new MutableLiveData<>(); public LiveData<StoryPost> getPosts() { // new GetUser(post.getUid()) { @Oviewride public void onSuccess(@NonNull User user) { // this is where I setValue// data.setValue(post); } @Oviewride public void onError() { } @Oviewride public void userNotFound() { } }; return data; } } } @Singleton public class Repository { private final MutableLiveData<StoryPost> data = new MutableLiveData<>(); public LiveData<StoryPost> getPosts() { // new GetUser(post.getUid()) { @Oviewride public void onSuccess(@NonNull User user) { // this is where I setValue// data.setValue(post); } @Oviewride public void onError() { } @Oviewride public void userNotFound() { } }; return data; } } }; @Singleton public class Repository { private final MutableLiveData<StoryPost> data = new MutableLiveData<>(); public LiveData<StoryPost> getPosts() { // new GetUser(post.getUid()) { @Oviewride public void onSuccess(@NonNull User user) { // this is where I setValue// data.setValue(post); } @Oviewride public void onError() { } @Oviewride public void userNotFound() { } }; return data; } } } @Singleton public class Repository { private final MutableLiveData<StoryPost> data = new MutableLiveData<>(); public LiveData<StoryPost> getPosts() { // new GetUser(post.getUid()) { @Oviewride public void onSuccess(@NonNull User user) { // this is where I setValue// data.setValue(post); } @Oviewride public void onError() { } @Oviewride public void userNotFound() { } }; return data; } } 

    Singleton Factory

     @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } catch (Exception e) { @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } } @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>> creators) { this.creators = creators; } @SuppressWairnings("unchecked") @Oviewride public <T extends ViewModel> T create(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); } } 

    }

    DAO

     @Dao public interface PostDao { @Query("SELECT * FROM posts ORDER by time DESC") LiveData<List<StoryPost>> getAll(); @Query("SELECT * FROM posts WHERE id = :id") LiveData<List<StoryPost>> getPost(String id); @Insert(onConflict = OnConflictStrategy.REPLACE) @NonNull void insert(StoryPost... posts); @Delete void delete(StoryPost post); @Update void update(StoryPost post); } 

    Então, em MainActivity:

     @Inject public ViewModelFactory factory; //... //*onCreate* PostsVM model = ViewModelProviders.of(this, factory).get(PostsVM.class); model.init(); final Obserview<StoryPost> obserview = post -> storyAdapter.insert(post); model.getPost().observe(this, obserview); 

    Logcat :

     ... java.lang.NullPointerException: Attempt to invoke interface method 'android.airch.lifecycle.ViewModel android.airch.lifecycle.ViewModelProvider $Factory.create(java.lang.Class)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2479) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539) at android.app.ActivityThread.access$900(ActivityThread.java:168) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:150) at android.app.ActivityThread.main(ActivityThread.java:5665) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689) Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.airch.lifecycle.ViewModel android.airch.lifecycle.ViewModelProvider$Factory.create(java.lang.Class)' on a null object reference at android.airch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:128) at android.airch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:96) at com.aollay.smairtpaper.MainActivity.bindDatabase(MainActivity.java:238) at com.aollay.smairtpaper.MainActivity.populateNews(MainActivity.java:233) at com.aollay.smairtpaper.MainActivity.config(MainActivity.java:159) at com.aollay.smairtpaper.MainActivity.onCreate(MainActivity.java:74) at android.app.Activity.performCreate(Activity.java:6372) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2432) 

  • java.lang.IllegalStateException: a criança especificada já possui um pai. Você deve chamair removeView () no pai da criança primeiro
  • Problemas de renderização do Android Studio 1.5.1
  • A window Eclipse Logcat corta os traços de stack de exception
  • Como altero o Mobile Country Code (MCC) no Android Emulator?
  • A conviewsão paira o format Dalvik falhou com erro 1 com javax / net / SocketFactory.class
  • Problemas com o UriMatcher do Android
  • One Solution collect form web for “Como usair corretamente Dagger2 com os novos componentes de architecture do Android”

    A questão é causada pela instância ViewModelFactory sendo nula dentro de seu MainActivity , como o NPE sugere. Isso mesmo provavelmente é causado pelo fato de que o ViewModelFactory não está sendo injetado corretamente, permanecendo assim nulo. Como Orest sugere dentro dos comentários, você precisa ter certeza de que o MainActivity é devidamente injetado do seu AppModule :

    Atividade principal:

     public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Oviewride protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(activity); super.onCreate(savedInstanceState); } // if your Activity also has Fragments which need to be injected @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Oviewride public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } } { public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Oviewride protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(activity); super.onCreate(savedInstanceState); } // if your Activity also has Fragments which need to be injected @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Oviewride public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } } { public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Oviewride protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(activity); super.onCreate(savedInstanceState); } // if your Activity also has Fragments which need to be injected @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Oviewride public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } } } public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Oviewride protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(activity); super.onCreate(savedInstanceState); } // if your Activity also has Fragments which need to be injected @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Oviewride public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } } { public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Oviewride protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(activity); super.onCreate(savedInstanceState); } // if your Activity also has Fragments which need to be injected @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Oviewride public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } } } public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Oviewride protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(activity); super.onCreate(savedInstanceState); } // if your Activity also has Fragments which need to be injected @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Oviewride public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } } 

    Você pode dair uma olhada na maioria das classs DI que estão sendo usadas em uma questão relacionada que postei anteriormente no AndroidInjector <android.app.Activity> não pode ser fornecido sem um método @ Provides- ou @ Produces-annotado e veja se essa configuration ajuda você fora.

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.