Send data to one activity's fragment from another activity? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?Stop EditText from gaining focus at Activity startupHow do I pass data between Activities in Android application?How to send an object from one Android Activity to another using Intents?Dilemma: when to use Fragments vs Activities:LiveData Object keeps being null after getValue() is calledList<> from Room Database is always nullViewModel, Room, LiveData, RecyclerView filter dataNo Data with RecyclerView, Data Binding and ViewModelList of One-to-Many Entities shows temporary entity from another ActivityTwo-way Data Binding, RecyclerView, ViewModel, Room, LiveData, Oh My

What is a Meta algorithm?

What is this single-engine low-wing propeller plane?

Why is black pepper both grey and black?

Did Xerox really develop the first LAN?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

Is the Standard Deduction better than Itemized when both are the same amount?

Why is "Consequences inflicted." not a sentence?

Bonus calculation: Am I making a mountain out of a molehill?

Is there a service that would inform me whenever a new direct route is scheduled from a given airport?

How to motivate offshore teams and trust them to deliver?

When -s is used with third person singular. What's its use in this context?

If 'B is more likely given A', then 'A is more likely given B'

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

List *all* the tuples!

3 doors, three guards, one stone

Should gear shift center itself while in neutral?

Is 1 ppb equal to 1 μg/kg?

Single word antonym of "flightless"

Do you forfeit tax refunds/credits if you aren't required to and don't file by April 15?

How widely used is the term Treppenwitz? Is it something that most Germans know?

What is the correct way to use the pinch test for dehydration?

How do I mention the quality of my school without bragging

Should I call the interviewer directly, if HR aren't responding?

Storing hydrofluoric acid before the invention of plastics



Send data to one activity's fragment from another activity?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?Stop EditText from gaining focus at Activity startupHow do I pass data between Activities in Android application?How to send an object from one Android Activity to another using Intents?Dilemma: when to use Fragments vs Activities:LiveData Object keeps being null after getValue() is calledList<> from Room Database is always nullViewModel, Room, LiveData, RecyclerView filter dataNo Data with RecyclerView, Data Binding and ViewModelList of One-to-Many Entities shows temporary entity from another ActivityTwo-way Data Binding, RecyclerView, ViewModel, Room, LiveData, Oh My



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








0















I have MainActivity which contains TabLayout with tabs: each tab is a fragment and each one has a RecyclerView. When I tap FAB in Main Activity, NewReminderActivity is opened.



I use Architecture Components: Entity(Reminder), DAO, Room, ViewModel, LiveData and Repository.



The question is:



  • Which methods should I use to deliver a new created reminder item into the fragment (which contains as mentioned above a RecyclerView?

I have some ideas, but could you help me please and give me a right direction for implementing:



1) I guess, I should deliver data to MainActivity, then from MainActivity to the fragment and use ViewModel as mentioned in https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing , am I right?



2) I guess I should use setResult() in NewReminderActivity, am I right?










share|improve this question



















  • 1





    I think a cleaner way would be to update the data first from NewReminderActivityViewModel to your Room database .Also subscribe your MainActivity's Fragments to listen to changes in Room database which will then automatically update your RecyclerView . MainActivity <-> MainActivityViewModel <-> Room Database NewReminderActivity <-> NewReminderActivityViewModel <-> RoomDatabase Would be glad to discuss on this further

    – Ayush Bansal
    Mar 10 at 19:10


















0















I have MainActivity which contains TabLayout with tabs: each tab is a fragment and each one has a RecyclerView. When I tap FAB in Main Activity, NewReminderActivity is opened.



I use Architecture Components: Entity(Reminder), DAO, Room, ViewModel, LiveData and Repository.



The question is:



  • Which methods should I use to deliver a new created reminder item into the fragment (which contains as mentioned above a RecyclerView?

I have some ideas, but could you help me please and give me a right direction for implementing:



1) I guess, I should deliver data to MainActivity, then from MainActivity to the fragment and use ViewModel as mentioned in https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing , am I right?



2) I guess I should use setResult() in NewReminderActivity, am I right?










share|improve this question



















  • 1





    I think a cleaner way would be to update the data first from NewReminderActivityViewModel to your Room database .Also subscribe your MainActivity's Fragments to listen to changes in Room database which will then automatically update your RecyclerView . MainActivity <-> MainActivityViewModel <-> Room Database NewReminderActivity <-> NewReminderActivityViewModel <-> RoomDatabase Would be glad to discuss on this further

    – Ayush Bansal
    Mar 10 at 19:10














0












0








0








I have MainActivity which contains TabLayout with tabs: each tab is a fragment and each one has a RecyclerView. When I tap FAB in Main Activity, NewReminderActivity is opened.



I use Architecture Components: Entity(Reminder), DAO, Room, ViewModel, LiveData and Repository.



The question is:



  • Which methods should I use to deliver a new created reminder item into the fragment (which contains as mentioned above a RecyclerView?

I have some ideas, but could you help me please and give me a right direction for implementing:



1) I guess, I should deliver data to MainActivity, then from MainActivity to the fragment and use ViewModel as mentioned in https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing , am I right?



2) I guess I should use setResult() in NewReminderActivity, am I right?










share|improve this question
















I have MainActivity which contains TabLayout with tabs: each tab is a fragment and each one has a RecyclerView. When I tap FAB in Main Activity, NewReminderActivity is opened.



I use Architecture Components: Entity(Reminder), DAO, Room, ViewModel, LiveData and Repository.



The question is:



  • Which methods should I use to deliver a new created reminder item into the fragment (which contains as mentioned above a RecyclerView?

I have some ideas, but could you help me please and give me a right direction for implementing:



1) I guess, I should deliver data to MainActivity, then from MainActivity to the fragment and use ViewModel as mentioned in https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing , am I right?



2) I guess I should use setResult() in NewReminderActivity, am I right?







android mvvm android-room android-livedata android-viewmodel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 11 at 16:04









EpicPandaForce

51.2k15136268




51.2k15136268










asked Mar 8 at 16:16









Вячеслав БорисовскийВячеслав Борисовский

122




122







  • 1





    I think a cleaner way would be to update the data first from NewReminderActivityViewModel to your Room database .Also subscribe your MainActivity's Fragments to listen to changes in Room database which will then automatically update your RecyclerView . MainActivity <-> MainActivityViewModel <-> Room Database NewReminderActivity <-> NewReminderActivityViewModel <-> RoomDatabase Would be glad to discuss on this further

    – Ayush Bansal
    Mar 10 at 19:10













  • 1





    I think a cleaner way would be to update the data first from NewReminderActivityViewModel to your Room database .Also subscribe your MainActivity's Fragments to listen to changes in Room database which will then automatically update your RecyclerView . MainActivity <-> MainActivityViewModel <-> Room Database NewReminderActivity <-> NewReminderActivityViewModel <-> RoomDatabase Would be glad to discuss on this further

    – Ayush Bansal
    Mar 10 at 19:10








1




1





I think a cleaner way would be to update the data first from NewReminderActivityViewModel to your Room database .Also subscribe your MainActivity's Fragments to listen to changes in Room database which will then automatically update your RecyclerView . MainActivity <-> MainActivityViewModel <-> Room Database NewReminderActivity <-> NewReminderActivityViewModel <-> RoomDatabase Would be glad to discuss on this further

– Ayush Bansal
Mar 10 at 19:10






I think a cleaner way would be to update the data first from NewReminderActivityViewModel to your Room database .Also subscribe your MainActivity's Fragments to listen to changes in Room database which will then automatically update your RecyclerView . MainActivity <-> MainActivityViewModel <-> Room Database NewReminderActivity <-> NewReminderActivityViewModel <-> RoomDatabase Would be glad to discuss on this further

– Ayush Bansal
Mar 10 at 19:10













1 Answer
1






active

oldest

votes


















0














If you are using Room, there is no reason for you to use setResult to transfer new item to any of these previous Fragments/Activities, because Room manages invalidation automatically.



@Dao
public interface MyDao
@Query("SELECT * FROM ITEM")
LiveData<List<Item>> getItemsWithChanges();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertItem(Item item);



Then



public class MyViewModel extends ViewModel 
private final LiveData<List<Item>> items;

public LiveData<List<Item>> getItems()
return items;


public MyViewModel(MyDao myDao)
items = myDao.getItemsWithChanges();




Then



public class MyFragment extends Fragment 
MyViewModel myViewModel;

@Override
protected void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
myViewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyViewModel.class);
myViewModel.getItems().observe(getViewLifecycleOwner(), (items) ->
if(items != null)
adapter.submitList(items);

);




In which case all you need to do in your second Activity is insert the new item, then finish out:



// imagine this is on background thread
myDao.insertItem(item);
runOnUiThread(() ->
finish();
);


And all your RecyclerViews will update with the new item (if they are part of the results as the condition matches it).






share|improve this answer























  • EpicPandaForce, thanks a lot!

    – Вячеслав Борисовский
    yesterday











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%2f55067040%2fsend-data-to-one-activitys-fragment-from-another-activity%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














If you are using Room, there is no reason for you to use setResult to transfer new item to any of these previous Fragments/Activities, because Room manages invalidation automatically.



@Dao
public interface MyDao
@Query("SELECT * FROM ITEM")
LiveData<List<Item>> getItemsWithChanges();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertItem(Item item);



Then



public class MyViewModel extends ViewModel 
private final LiveData<List<Item>> items;

public LiveData<List<Item>> getItems()
return items;


public MyViewModel(MyDao myDao)
items = myDao.getItemsWithChanges();




Then



public class MyFragment extends Fragment 
MyViewModel myViewModel;

@Override
protected void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
myViewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyViewModel.class);
myViewModel.getItems().observe(getViewLifecycleOwner(), (items) ->
if(items != null)
adapter.submitList(items);

);




In which case all you need to do in your second Activity is insert the new item, then finish out:



// imagine this is on background thread
myDao.insertItem(item);
runOnUiThread(() ->
finish();
);


And all your RecyclerViews will update with the new item (if they are part of the results as the condition matches it).






share|improve this answer























  • EpicPandaForce, thanks a lot!

    – Вячеслав Борисовский
    yesterday















0














If you are using Room, there is no reason for you to use setResult to transfer new item to any of these previous Fragments/Activities, because Room manages invalidation automatically.



@Dao
public interface MyDao
@Query("SELECT * FROM ITEM")
LiveData<List<Item>> getItemsWithChanges();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertItem(Item item);



Then



public class MyViewModel extends ViewModel 
private final LiveData<List<Item>> items;

public LiveData<List<Item>> getItems()
return items;


public MyViewModel(MyDao myDao)
items = myDao.getItemsWithChanges();




Then



public class MyFragment extends Fragment 
MyViewModel myViewModel;

@Override
protected void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
myViewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyViewModel.class);
myViewModel.getItems().observe(getViewLifecycleOwner(), (items) ->
if(items != null)
adapter.submitList(items);

);




In which case all you need to do in your second Activity is insert the new item, then finish out:



// imagine this is on background thread
myDao.insertItem(item);
runOnUiThread(() ->
finish();
);


And all your RecyclerViews will update with the new item (if they are part of the results as the condition matches it).






share|improve this answer























  • EpicPandaForce, thanks a lot!

    – Вячеслав Борисовский
    yesterday













0












0








0







If you are using Room, there is no reason for you to use setResult to transfer new item to any of these previous Fragments/Activities, because Room manages invalidation automatically.



@Dao
public interface MyDao
@Query("SELECT * FROM ITEM")
LiveData<List<Item>> getItemsWithChanges();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertItem(Item item);



Then



public class MyViewModel extends ViewModel 
private final LiveData<List<Item>> items;

public LiveData<List<Item>> getItems()
return items;


public MyViewModel(MyDao myDao)
items = myDao.getItemsWithChanges();




Then



public class MyFragment extends Fragment 
MyViewModel myViewModel;

@Override
protected void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
myViewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyViewModel.class);
myViewModel.getItems().observe(getViewLifecycleOwner(), (items) ->
if(items != null)
adapter.submitList(items);

);




In which case all you need to do in your second Activity is insert the new item, then finish out:



// imagine this is on background thread
myDao.insertItem(item);
runOnUiThread(() ->
finish();
);


And all your RecyclerViews will update with the new item (if they are part of the results as the condition matches it).






share|improve this answer













If you are using Room, there is no reason for you to use setResult to transfer new item to any of these previous Fragments/Activities, because Room manages invalidation automatically.



@Dao
public interface MyDao
@Query("SELECT * FROM ITEM")
LiveData<List<Item>> getItemsWithChanges();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertItem(Item item);



Then



public class MyViewModel extends ViewModel 
private final LiveData<List<Item>> items;

public LiveData<List<Item>> getItems()
return items;


public MyViewModel(MyDao myDao)
items = myDao.getItemsWithChanges();




Then



public class MyFragment extends Fragment 
MyViewModel myViewModel;

@Override
protected void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
myViewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MyViewModel.class);
myViewModel.getItems().observe(getViewLifecycleOwner(), (items) ->
if(items != null)
adapter.submitList(items);

);




In which case all you need to do in your second Activity is insert the new item, then finish out:



// imagine this is on background thread
myDao.insertItem(item);
runOnUiThread(() ->
finish();
);


And all your RecyclerViews will update with the new item (if they are part of the results as the condition matches it).







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 11 at 16:18









EpicPandaForceEpicPandaForce

51.2k15136268




51.2k15136268












  • EpicPandaForce, thanks a lot!

    – Вячеслав Борисовский
    yesterday

















  • EpicPandaForce, thanks a lot!

    – Вячеслав Борисовский
    yesterday
















EpicPandaForce, thanks a lot!

– Вячеслав Борисовский
yesterday





EpicPandaForce, thanks a lot!

– Вячеслав Борисовский
yesterday



















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%2f55067040%2fsend-data-to-one-activitys-fragment-from-another-activity%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

1928 у кіно

Захаров Федір Захарович

Ель Греко