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;
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.
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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.
add a comment |
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);
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
edited Mar 23 at 13:54
TheRealBilaal
5481517
5481517
answered Mar 22 at 21:56
Vygintas BVygintas B
1,255724
1,255724
add a comment |
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
edited Mar 22 at 22:12
answered Mar 22 at 22:06
Amrat SinghAmrat Singh
238211
238211
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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