Solution 1 :
You can start Activity2 using startActivityForResult
and then call setResult
to return a value.
Or you can use a ViewModel
(common class) to share data between activities.
The difference between a using a variable in a ViewModel
and saving data to SharedPreferences
is that the variables in a ViewModel
are not persisted and the information will be lost when the app is closed.
Solution 2 :
pass and get data into multiple activity for this i recommend you to use the shared preference to get and set the data into multiple activity. and you can also use to local storage. but if you are using 2 activity than you can use on activity Result .
Problem :
There are several answers on the site, but it looks like I need a more clear answer.
Assume Activity1 contains a TextView and Activity2 contains a RecyclerView. If some data on Activity2 is modified, Activity1 should be informed. There are two ways to Activity1 from Activity2:
- A normal button on the layout.
- “The” Back Button.
It looks possible to call startActivity()
with putExtra()
inside onBackPressed()
. However this does not look efficient to me, as it will reload the UI, reload data, restart initial checks etc. Therefore, I’d like to send a flag so that “only the essential” changes can be made in Activity1 -by decoding the flag with an if
statement in onStart()
I suppose(?). How do I achieve this with both buttons.
Bonus question:
- It is possible to use sharedPreferences to transfer data.
- It is possible to use a common class to transfer data.
Is using a common class faster than sharedPreferences, especially if I need to transfer data often? I read something like: “once sharedPreferences is loaded into RAM it is in the RAM till the closing of the app, so it is not that slow.”
Also, is using common class robust enough to handle unexpected behavior like closing the app suddenly, or receiving a call etc.?
Comments
Comment posted by Tenfour04
Search for startActivityForResult.
Comment posted by this
Thank you. What if user jumps to Activity3 from Activity2? Will
Comment posted by Juan Cruz Soler
You have to call
Comment posted by Xfce4
Actually I have a transfer structure that depends on
Comment posted by Xfce4
Thanks. I also used sharedPreferences. But everytime activity1 starts I load a list from sharedPreferences, which does not look so efficient. Maybe it is better to store flags into sharedPreferences and load the list only if necessary.
Comment posted by Amit pandey
you can use realm to store the data from server its essay
Comment posted by Xfce4
Thanks for the tip. Is there an open-source alternative?