title: How to use ViewModel in a fragment?
body: <p>I'm using the MVVM architecture. I have an activity and a few fragments, I would like to make a request in the API in the activity, and then using ViewModel, thanks to the obtained data, to display them in the fragment. How should I do this? My current solution that doesn't work:</p>
  <p>Activity:</p>
  <pre><code>viewModelRoutesFragment = new ViewModelProvider(this).get(ViewModelRoutesFragment.class);
  viewModelRoutesFragment.init();
  </code></pre>
  <p>Fragment:</p>
  <pre><code>viewModelRoutesFragment = new ViewModelProvider(this).get(ViewModelRoutesFragment.class);
  viewModelRoutesFragment.getRoutes().observe(getActivity(), new Observer&lt;List&lt;RoutesResponse&gt;&gt;() {
      @Override
      public void onChanged(List&lt;RoutesResponse&gt; routes) {
  
                  //Show data
      }
  });
  </code></pre>
  <p>Repository:</p>
  <pre><code>public class RemoteRepository {
  
  private ApiRequest apiRequest;
  private MutableLiveData&lt;List&lt;RoutesResponse&gt;&gt; routes = new MutableLiveData&lt;&gt;();
  
  public RemoteRepository() {
      apiRequest = RetrofitRequest.getInstance().create(ApiRequest.class);
  }
  
  public MutableLiveData&lt;List&lt;RoutesResponse&gt;&gt; getRoutes() {
  
      apiRequest.getRoutes()
              .enqueue(new Callback&lt;List&lt;RoutesResponse&gt;&gt;() {
                  @Override
                  public void onResponse(Call&lt;List&lt;RoutesResponse&gt;&gt; call, Response&lt;List&lt;RoutesResponse&gt;&gt; response) {
  
                      if (response.isSuccessful())
                          routes.setValue(response.body());
                  }
  
                  @Override
                  public void onFailure(Call&lt;List&lt;RoutesResponse&gt;&gt; call, Throwable t) {
                      Log.i(&quot;Failure&quot;, &quot;Fail!&quot;);
                  }
              });
  
          return routes;
      }
  }
  </code></pre>
  <p>ViewModel:</p>
  <pre><code>public class ViewModelRoutesFragment extends AndroidViewModel {
  
  private RemoteRepository remoteRepository;
  private LiveData&lt;List&lt;RoutesResponse&gt;&gt; routes;
  
  public ViewModelRoutesFragment(@NonNull Application application) {
      super(application);
  }
  
  public void init() {
      remoteRepository = new RemoteRepository();
      routes = remoteRepository.getRoutes();
  }
  
  public LiveData&lt;List&lt;RoutesResponse&gt;&gt; getRoutes() {
          return routes;
      }
  }
  </code></pre>
  <p>Currently getting a null error. How can I avoid it properly?</p>
  <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference
  </code></pre>