Create ViewModel with ApplicationWhat exactly is the difference between Android View Model and a Singleton classIs quitting an application frowned upon?Using the Android Application class to persist dataDialog throwing "Unable to add window — token null is not for an application” with getApplication() as contextUnderstanding Fragment's setRetainInstance(boolean)Once for all, how to correctly save instance state of Fragments in back stack?What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?Warning: This AsyncTask class should be static or leaks might occurAndroid Architecture Components ViewModel ContextObserving LiveData from ViewModelCan I make the LiveData static?

My suffix is short for the place where you are…

Which industry am I working in? Software development or financial services?

What are the differences between credential stuffing and password spraying?

CRT Oscilloscope - part of the plot is missing

What was the state of the German rail system in 1944?

My ID is expired, can I fly to the Bahamas with my passport?

Why is Arya visibly scared in the library in S8E3?

Junior developer struggles: how to communicate with management?

Should my Json storage handle exceptions?

Is there a legal ground for stripping the UK of its UN Veto if Scotland and/or N.Ireland split from the UK?

Missed the connecting flight, separate tickets on same airline - who is responsible?

What happens if I start too many background jobs?

Father and Son and Grandsons

Has any spacecraft ever had the ability to directly communicate with civilian air traffic control?

What happens to the Time Stone

Returning the outputs of a nested structure

I caught several of my students plagiarizing. Could it be my fault as a teacher?

What are the spoon bit of a spoon and fork bit of a fork called?

Number of seconds in 6 weeks

Upside-Down Pyramid Addition...REVERSED!

For a benzene shown in a skeletal structure, what does a substituent to the center of the ring mean?

Besides the up and down quark, what other quarks are present in daily matter around us?

How to generate a customised histogram with pgf plots?

Selecting a secure PIN for building access



Create ViewModel with Application


What exactly is the difference between Android View Model and a Singleton classIs quitting an application frowned upon?Using the Android Application class to persist dataDialog throwing "Unable to add window — token null is not for an application” with getApplication() as contextUnderstanding Fragment's setRetainInstance(boolean)Once for all, how to correctly save instance state of Fragments in back stack?What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?Warning: This AsyncTask class should be static or leaks might occurAndroid Architecture Components ViewModel ContextObserving LiveData from ViewModelCan I make the LiveData static?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am trying to set data onto the ViewModel in a file in which I do not wish to hold any activity references.



Class A -> set data onto the LiveData in ViewModel
Has an Application class reference but does not hold activity or fragment



Class B -> read data from the LiveData in ViewModel
Has a reference to the activity.



Class B can be destroyed and recreated along with the Activity's config changes.
Class A is persistent in memory and keeps setting data to the LiveData



Problem: ViewModelProviders.of(activity or fragment).get()
ViewProviders need activity or fragment instance.










share|improve this question






















  • Do you have some code to show what u have tried already? Maybe you could refer to the activity as owner even if it is not holding it.

    – Daniel Spiess
    Mar 22 at 21:37

















1















I am trying to set data onto the ViewModel in a file in which I do not wish to hold any activity references.



Class A -> set data onto the LiveData in ViewModel
Has an Application class reference but does not hold activity or fragment



Class B -> read data from the LiveData in ViewModel
Has a reference to the activity.



Class B can be destroyed and recreated along with the Activity's config changes.
Class A is persistent in memory and keeps setting data to the LiveData



Problem: ViewModelProviders.of(activity or fragment).get()
ViewProviders need activity or fragment instance.










share|improve this question






















  • Do you have some code to show what u have tried already? Maybe you could refer to the activity as owner even if it is not holding it.

    – Daniel Spiess
    Mar 22 at 21:37













1












1








1








I am trying to set data onto the ViewModel in a file in which I do not wish to hold any activity references.



Class A -> set data onto the LiveData in ViewModel
Has an Application class reference but does not hold activity or fragment



Class B -> read data from the LiveData in ViewModel
Has a reference to the activity.



Class B can be destroyed and recreated along with the Activity's config changes.
Class A is persistent in memory and keeps setting data to the LiveData



Problem: ViewModelProviders.of(activity or fragment).get()
ViewProviders need activity or fragment instance.










share|improve this question














I am trying to set data onto the ViewModel in a file in which I do not wish to hold any activity references.



Class A -> set data onto the LiveData in ViewModel
Has an Application class reference but does not hold activity or fragment



Class B -> read data from the LiveData in ViewModel
Has a reference to the activity.



Class B can be destroyed and recreated along with the Activity's config changes.
Class A is persistent in memory and keeps setting data to the LiveData



Problem: ViewModelProviders.of(activity or fragment).get()
ViewProviders need activity or fragment instance.







android android-livedata android-viewmodel






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 21:05









dcanh121dcanh121

2,98573074




2,98573074












  • Do you have some code to show what u have tried already? Maybe you could refer to the activity as owner even if it is not holding it.

    – Daniel Spiess
    Mar 22 at 21:37

















  • Do you have some code to show what u have tried already? Maybe you could refer to the activity as owner even if it is not holding it.

    – Daniel Spiess
    Mar 22 at 21:37
















Do you have some code to show what u have tried already? Maybe you could refer to the activity as owner even if it is not holding it.

– Daniel Spiess
Mar 22 at 21:37





Do you have some code to show what u have tried already? Maybe you could refer to the activity as owner even if it is not holding it.

– Daniel Spiess
Mar 22 at 21:37












2 Answers
2






active

oldest

votes


















0














ViewModels are strongly tied to Activity's and Fragment's lifecycle so you cannot use them with application context and need to use Activity's and Fragment's context.



If you want to share data between fragments you can use getActivity() to get the same ViewModel which will hold your data and will survive as long as your Activity is in scope.






share|improve this answer
































    -1














    You can use AndroidViewModel, it is attached with application lifecycle.



    An example:



    public class ProductViewModel extends AndroidViewModel 


        private final LiveData<ProductEntity> mObservableProduct;


        public ObservableField<ProductEntity> product = new ObservableField<>();


        private final int mProductId;


        private final LiveData<List<CommentEntity>> mObservableComments;


        public ProductViewModel(@NonNull Application application, DataRepository repository,

                final int productId)

            super(application);

            mProductId = productId;


            mObservableComments = repository.loadComments(mProductId);

            mObservableProduct = repository.loadProduct(mProductId);

        


        /**

    * Expose the LiveData Comments query so the UI can observe it.

    */

        public LiveData<List<CommentEntity>> getComments()

            return mObservableComments;

        


        public LiveData<ProductEntity> getObservableProduct()

            return mObservableProduct;

        


        public void setProduct(ProductEntity product)

            this.product.set(product);

        


        /**

    * A creator is used to inject the product ID into the ViewModel

    * <p>

    * This creator is to showcase how to inject dependencies into ViewModels. It's not

    * actually necessary in this case, as the product ID can be passed in a public method.

    */

        public static class Factory extends ViewModelProvider.NewInstanceFactory


            @NonNull

            private final Application mApplication;


            private final int mProductId;


            private final DataRepository mRepository;


            public Factory(@NonNull Application application, int productId)

                mApplication = application;

                mProductId = productId;

                mRepository = ((BasicApp) application).getRepository();

            


            @Override

            public <T extends ViewModel> T create(Class<T> modelClass)

                //noinspection unchecked

                return (T) new ProductViewModel(mApplication, mRepository, mProductId);

            

        







    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307761%2fcreate-viewmodel-with-application%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      ViewModels are strongly tied to Activity's and Fragment's lifecycle so you cannot use them with application context and need to use Activity's and Fragment's context.



      If you want to share data between fragments you can use getActivity() to get the same ViewModel which will hold your data and will survive as long as your Activity is in scope.






      share|improve this answer





























        0














        ViewModels are strongly tied to Activity's and Fragment's lifecycle so you cannot use them with application context and need to use Activity's and Fragment's context.



        If you want to share data between fragments you can use getActivity() to get the same ViewModel which will hold your data and will survive as long as your Activity is in scope.






        share|improve this answer



























          0












          0








          0







          ViewModels are strongly tied to Activity's and Fragment's lifecycle so you cannot use them with application context and need to use Activity's and Fragment's context.



          If you want to share data between fragments you can use getActivity() to get the same ViewModel which will hold your data and will survive as long as your Activity is in scope.






          share|improve this answer















          ViewModels are strongly tied to Activity's and Fragment's lifecycle so you cannot use them with application context and need to use Activity's and Fragment's context.



          If you want to share data between fragments you can use getActivity() to get the same ViewModel which will hold your data and will survive as long as your Activity is in scope.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 23 at 13:54









          TheRealBilaal

          5481517




          5481517










          answered Mar 22 at 21:56









          Vygintas BVygintas B

          1,255724




          1,255724























              -1














              You can use AndroidViewModel, it is attached with application lifecycle.



              An example:



              public class ProductViewModel extends AndroidViewModel 


                  private final LiveData<ProductEntity> mObservableProduct;


                  public ObservableField<ProductEntity> product = new ObservableField<>();


                  private final int mProductId;


                  private final LiveData<List<CommentEntity>> mObservableComments;


                  public ProductViewModel(@NonNull Application application, DataRepository repository,

                          final int productId)

                      super(application);

                      mProductId = productId;


                      mObservableComments = repository.loadComments(mProductId);

                      mObservableProduct = repository.loadProduct(mProductId);

                  


                  /**

              * Expose the LiveData Comments query so the UI can observe it.

              */

                  public LiveData<List<CommentEntity>> getComments()

                      return mObservableComments;

                  


                  public LiveData<ProductEntity> getObservableProduct()

                      return mObservableProduct;

                  


                  public void setProduct(ProductEntity product)

                      this.product.set(product);

                  


                  /**

              * A creator is used to inject the product ID into the ViewModel

              * <p>

              * This creator is to showcase how to inject dependencies into ViewModels. It's not

              * actually necessary in this case, as the product ID can be passed in a public method.

              */

                  public static class Factory extends ViewModelProvider.NewInstanceFactory


                      @NonNull

                      private final Application mApplication;


                      private final int mProductId;


                      private final DataRepository mRepository;


                      public Factory(@NonNull Application application, int productId)

                          mApplication = application;

                          mProductId = productId;

                          mRepository = ((BasicApp) application).getRepository();

                      


                      @Override

                      public <T extends ViewModel> T create(Class<T> modelClass)

                          //noinspection unchecked

                          return (T) new ProductViewModel(mApplication, mRepository, mProductId);

                      

                  







              share|improve this answer





























                -1














                You can use AndroidViewModel, it is attached with application lifecycle.



                An example:



                public class ProductViewModel extends AndroidViewModel 


                    private final LiveData<ProductEntity> mObservableProduct;


                    public ObservableField<ProductEntity> product = new ObservableField<>();


                    private final int mProductId;


                    private final LiveData<List<CommentEntity>> mObservableComments;


                    public ProductViewModel(@NonNull Application application, DataRepository repository,

                            final int productId)

                        super(application);

                        mProductId = productId;


                        mObservableComments = repository.loadComments(mProductId);

                        mObservableProduct = repository.loadProduct(mProductId);

                    


                    /**

                * Expose the LiveData Comments query so the UI can observe it.

                */

                    public LiveData<List<CommentEntity>> getComments()

                        return mObservableComments;

                    


                    public LiveData<ProductEntity> getObservableProduct()

                        return mObservableProduct;

                    


                    public void setProduct(ProductEntity product)

                        this.product.set(product);

                    


                    /**

                * A creator is used to inject the product ID into the ViewModel

                * <p>

                * This creator is to showcase how to inject dependencies into ViewModels. It's not

                * actually necessary in this case, as the product ID can be passed in a public method.

                */

                    public static class Factory extends ViewModelProvider.NewInstanceFactory


                        @NonNull

                        private final Application mApplication;


                        private final int mProductId;


                        private final DataRepository mRepository;


                        public Factory(@NonNull Application application, int productId)

                            mApplication = application;

                            mProductId = productId;

                            mRepository = ((BasicApp) application).getRepository();

                        


                        @Override

                        public <T extends ViewModel> T create(Class<T> modelClass)

                            //noinspection unchecked

                            return (T) new ProductViewModel(mApplication, mRepository, mProductId);

                        

                    







                share|improve this answer



























                  -1












                  -1








                  -1







                  You can use AndroidViewModel, it is attached with application lifecycle.



                  An example:



                  public class ProductViewModel extends AndroidViewModel 


                      private final LiveData<ProductEntity> mObservableProduct;


                      public ObservableField<ProductEntity> product = new ObservableField<>();


                      private final int mProductId;


                      private final LiveData<List<CommentEntity>> mObservableComments;


                      public ProductViewModel(@NonNull Application application, DataRepository repository,

                              final int productId)

                          super(application);

                          mProductId = productId;


                          mObservableComments = repository.loadComments(mProductId);

                          mObservableProduct = repository.loadProduct(mProductId);

                      


                      /**

                  * Expose the LiveData Comments query so the UI can observe it.

                  */

                      public LiveData<List<CommentEntity>> getComments()

                          return mObservableComments;

                      


                      public LiveData<ProductEntity> getObservableProduct()

                          return mObservableProduct;

                      


                      public void setProduct(ProductEntity product)

                          this.product.set(product);

                      


                      /**

                  * A creator is used to inject the product ID into the ViewModel

                  * <p>

                  * This creator is to showcase how to inject dependencies into ViewModels. It's not

                  * actually necessary in this case, as the product ID can be passed in a public method.

                  */

                      public static class Factory extends ViewModelProvider.NewInstanceFactory


                          @NonNull

                          private final Application mApplication;


                          private final int mProductId;


                          private final DataRepository mRepository;


                          public Factory(@NonNull Application application, int productId)

                              mApplication = application;

                              mProductId = productId;

                              mRepository = ((BasicApp) application).getRepository();

                          


                          @Override

                          public <T extends ViewModel> T create(Class<T> modelClass)

                              //noinspection unchecked

                              return (T) new ProductViewModel(mApplication, mRepository, mProductId);

                          

                      







                  share|improve this answer















                  You can use AndroidViewModel, it is attached with application lifecycle.



                  An example:



                  public class ProductViewModel extends AndroidViewModel 


                      private final LiveData<ProductEntity> mObservableProduct;


                      public ObservableField<ProductEntity> product = new ObservableField<>();


                      private final int mProductId;


                      private final LiveData<List<CommentEntity>> mObservableComments;


                      public ProductViewModel(@NonNull Application application, DataRepository repository,

                              final int productId)

                          super(application);

                          mProductId = productId;


                          mObservableComments = repository.loadComments(mProductId);

                          mObservableProduct = repository.loadProduct(mProductId);

                      


                      /**

                  * Expose the LiveData Comments query so the UI can observe it.

                  */

                      public LiveData<List<CommentEntity>> getComments()

                          return mObservableComments;

                      


                      public LiveData<ProductEntity> getObservableProduct()

                          return mObservableProduct;

                      


                      public void setProduct(ProductEntity product)

                          this.product.set(product);

                      


                      /**

                  * A creator is used to inject the product ID into the ViewModel

                  * <p>

                  * This creator is to showcase how to inject dependencies into ViewModels. It's not

                  * actually necessary in this case, as the product ID can be passed in a public method.

                  */

                      public static class Factory extends ViewModelProvider.NewInstanceFactory


                          @NonNull

                          private final Application mApplication;


                          private final int mProductId;


                          private final DataRepository mRepository;


                          public Factory(@NonNull Application application, int productId)

                              mApplication = application;

                              mProductId = productId;

                              mRepository = ((BasicApp) application).getRepository();

                          


                          @Override

                          public <T extends ViewModel> T create(Class<T> modelClass)

                              //noinspection unchecked

                              return (T) new ProductViewModel(mApplication, mRepository, mProductId);

                          

                      








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 22 at 22:12

























                  answered Mar 22 at 22:06









                  Amrat SinghAmrat Singh

                  238211




                  238211



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307761%2fcreate-viewmodel-with-application%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해