I have an activity that contains a number of fragments. Each fragment has a viewModel scoped to its lifetime with some logic inside. The host activity has a viewModel too, including some code to show a popup-style message.
I want my fragment viewModels to be able to post messages to this popup. However, how could I access the activity-viewModel from inside one of my fragment-viewModels?
I'll write some exemplary Kotlin code, but the question is not specific to Kotlin since it's more of an architectural issue.
class MyActivityViewModel {
...
popupMessage = MutableLiveData<String>("") // is observed by my activity
fun postMessage(text: String) {
popupMessage.value = text
}
}
class MyFragmentAViewModel {
...
fun someFunctionA() {
// want to call ActivityViewModel's postMessage from here
}
}
class MyFragmentBViewModel {
...
fun someFunctionB() {
// want to call ActivityViewModel's postMessage from here too
}
}
I can't easily call ViewModelProvider since I'd rather not keep a reference to an Activity in my viewModel. The only direct option I see is to pass the activity-viewModel to the fragment-viewModels through the constructor or an init() method. That should be safe since the parent viewModel's lifetime should exceed the fragment viewModels' lifetime. I think.
Still, that solution rubs me the wrong way.
Are there any other alternatives? Or perhaps an entirely different approach to the issue?
Here's the thought of a greenhorn:
Can't you tell the activity that your fragment wants to use its method?
If you
Make an interface with a method a la "fragmentAWantsToUsePostMessage" in your fragment
Implement the interface in the activity, so that every time fragmentAWantsToUsePostMessage is called, the activity calls postMessage
Get a reference to the implementation of the interface in your fragment
Use that reference when the fragment needs to call "post message"
Shouldn't that work? Or is that against your "not keeping a reference"?
As I said: I'm new to all of this, so I might be completely wrong.
I can see that there's a post on medium that might be relevant: How to Communicate between Fragment and Activity
This question is mostly to solicit opinions on the best way to handle my app. I have three fragments being handled by one activity. Fragment A has one clickable element the photo and Fragment B has 4 clickable elements the buttons. The other fragment just displays details when the photo is clicked. I am using ActionBarSherlock.
The forward and back buttons need to change the photo to the next or previous poses, respectively. I could keep the photo and the buttons in the same fragment, but wanted to keep them separate in case I wanted to rearrange them in a tablet.
I need some advice - should I combine Fragments A and B? If not, I will need to figure out how to implement an interface for 3 clickable items.
I considered using Roboguice, but I am already extending using SherlockFragmentActivity so that's a no go. I saw mention of Otto, but I didn't see good tutorials on how to include in a project. What do you think best design practice should be?
I also need help figuring out how to communicate between a fragment and an activity. I'd like to keep some data "global" in the application, like the pose id. Is there some example code I can see besides the stock android developer's information? That is not all that helpful.
BTW, I'm already storing all the information about each pose in a SQLite database. That's the easy part.
The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.
Once it has implemented that interface, you could do anything you want in the method it overrides.
The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.
There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.
I hope this was helpful to you!
The suggested method for communicating between fragments is to use callbacks\listeners that are managed by your main Activity.
I think the code on this page is pretty clear:
http://developer.android.com/training/basics/fragments/communicating.html
You can also reference the IO 2012 Schedule app, which is designed to be a de-facto reference app. It can be found here:
http://code.google.com/p/iosched/
Also, here is a SO question with good info:
How to pass data between fragments
It is implemented by a Callback interface:
First of all, we have to make an interface:
public interface UpdateFrag {
void updatefrag();
}
In the Activity do the following code:
UpdateFrag updatfrag ;
public void updateApi(UpdateFrag listener) {
updatfrag = listener;
}
from the event from where the callback has to fire in the Activity:
updatfrag.updatefrag();
In the Fragment implement the interface in CreateView do the
following code:
((Home)getActivity()).updateApi(new UpdateFrag() {
#Override
public void updatefrag() {
.....your stuff......
}
});
To communicate between an Activity and Fragments, there are several options, but after lots of reading and many experiences, I found out that it could be resumed this way:
Activity wants to communicate with child Fragment => Simply write public methods in your Fragment class, and let the Activity call them
Fragment wants to communicate with the parent Activity => This requires a bit more of work, as the official Android link https://developer.android.com/training/basics/fragments/communicating suggests, it would be a great idea to define an interface that will be implemented by the Activity, and which will establish a contract for any Activity that wants to communicate with that Fragment. For example, if you have FragmentA, which wants to communicate with any activity that includes it, then define the FragmentAInterface which will define what method can the FragmentA call for the activities that decide to use it.
A Fragment wants to communicate with other Fragment => This is the case where you get the most 'complicated' situation. Since you could potentially need to pass data from FragmentA to FragmentB and viceversa, that could lead us to defining 2 interfaces, FragmentAInterface which will be implemented by FragmentB and FragmentAInterface which will be implemented by FragmentA. That will start making things messy. And imagine if you have a few more Fragments on place, and even the parent activity wants to communicate with them. Well, this case is a perfect moment to establish a shared ViewModel for the activity and it's fragments. More info here https://developer.android.com/topic/libraries/architecture/viewmodel . Basically, you need to define a SharedViewModel class, that has all the data you want to share between the activity and the fragments that will be in need of communicating data among them.
The ViewModel case, makes things pretty simpler at the end, since you don't have to add extra logic that makes things dirty in the code and messy. Plus it will allow you to separate the gathering (through calls to an SQLite Database or an API) of data from the Controller (activities and fragments).
I made a annotation library that can do the cast for you. check this out.
https://github.com/zeroarst/callbackfragment/
#CallbackFragment
public class MyFragment extends Fragment {
#Callback
interface FragmentCallback {
void onClickButton(MyFragment fragment);
}
private FragmentCallback mCallback;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt1
mCallback.onClickButton(this);
break;
case R.id.bt2
// Because we give mandatory = false so this might be null if not implemented by the host.
if (mCallbackNotForce != null)
mCallbackNotForce.onClickButton(this);
break;
}
}
}
It then generates a subclass of your fragment. And just add it to FragmentManager.
public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), "MY_FRAGM")
.commit();
}
Toast mToast;
#Override
public void onClickButton(MyFragment fragment) {
if (mToast != null)
mToast.cancel();
mToast = Toast.makeText(this, "Callback from " + fragment.getTag(), Toast.LENGTH_SHORT);
mToast.show();
}
}
Google Recommended Method
If you take a look at this page you can see that Google suggests you use the ViewModel to share data between Fragment and Activity.
Add this dependency:
implementation "androidx.activity:activity-ktx:$activity_version"
First, define the ViewModel you are going to use to pass data.
class ItemViewModel : ViewModel() {
private val mutableSelectedItem = MutableLiveData<Item>()
val selectedItem: LiveData<Item> get() = mutableSelectedItem
fun selectItem(item: Item) {
mutableSelectedItem.value = item
}
}
Second, instantiate the ViewModel inside the Activity.
class MainActivity : AppCompatActivity() {
// Using the viewModels() Kotlin property delegate from the activity-ktx
// artifact to retrieve the ViewModel in the activity scope
private val viewModel: ItemViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.selectedItem.observe(this, Observer { item ->
// Perform an action with the latest item data
})
}
}
Third, instantiate the ViewModel inside the Fragment.
class ListFragment : Fragment() {
// Using the activityViewModels() Kotlin property delegate from the
// fragment-ktx artifact to retrieve the ViewModel in the activity scope
private val viewModel: ItemViewModel by activityViewModels()
// Called when the item is clicked
fun onItemClicked(item: Item) {
// Set a new item
viewModel.selectItem(item)
}
}
You can now edit this code creating new observers or settings methods.
There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.
My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.
You can subscribe to events in your activity and then you can post that events in your fragments etc.
Here on my blog post you can find more detail about this pattern and also an example project to show the usage.
I'm not sure I really understood what you want to do, but the suggested way to communicate between fragments is to use callbacks with the Activity, never directly between fragments. See here http://developer.android.com/training/basics/fragments/communicating.html
You can create declare a public interface with a function declaration in the fragment and implement the interface in the activity. Then you can call the function from the fragment.
I am using Intents to communicate actions back to the main activity. The main activity is listening to these by overriding onNewIntent(Intent intent). The main activity translates these actions to the corresponding fragments for example.
So you can do something like this:
public class MainActivity extends Activity {
public static final String INTENT_ACTION_SHOW_FOO = "show_foo";
public static final String INTENT_ACTION_SHOW_BAR = "show_bar";
#Override
protected void onNewIntent(Intent intent) {
routeIntent(intent);
}
private void routeIntent(Intent intent) {
String action = intent.getAction();
if (action != null) {
switch (action) {
case INTENT_ACTION_SHOW_FOO:
// for example show the corresponding fragment
loadFragment(FooFragment);
break;
case INTENT_ACTION_SHOW_BAR:
loadFragment(BarFragment);
break;
}
}
}
Then inside any fragment to show the foo fragment:
Intent intent = new Intent(context, MainActivity.class);
intent.setAction(INTENT_ACTION_SHOW_FOO);
// Prevent activity to be re-instantiated if it is already running.
// Instead, the onNewEvent() is triggered
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
getContext().startActivity(intent);
There is the latest techniques to communicate fragment to activity without any interface follow the steps
Step 1- Add the dependency in gradle
implementation 'androidx.fragment:fragment:1.3.0-rc01'
As a little example: Take a website where you land on a login page and after a successful login getting directed to the main page where on the left side you'd have a menu and on the right side a content are where everything gets loaded when clicking a link in the menu. In the menu I'd have multiple stores where each store would have its own settings. Those settings would be initialized with an id to determine which content the view should display.
For the history mapper I guess one would have something like this:
/#LoginPlace:login
/#MainPlace:home
/#MainPlace:storeSettings?id=<id>
/#MainPlace:userSettings
etc..
In [2] it says
"In order to be accessible via a URL, an Activity needs a corresponding Place."
Which sounds to me like I should have a LoginActivity and a MainActiviy since after all LoginActivity is the first Place I arrive when I come to my website and MainActivity is the place I go when I am successfully logged in.
I'd have someting like this:
public class LoginActivity extends AbstractActivity implements LoginView.Presenter {
// ..
private void onLoginSuccess() {
this.clientFactory.getPlaceController().goTo(new MainPlace());
}
}
public class MainActivity extends AbstractActivity implements MainView.Presenter {
// ..
}
and of course have respective view LoginView and MainView.
This is how AppActivityMapper.getActivity() would look like:
#Override
public Activity getActivity(Place place) {
if (place instanceof LoginPlace) {
return new LoginActivity((LoginPlace) place, clientFactory);
} else if (place instanceof MainPlace) {
return new MainActivity((MainPlace) place, clientFactory);
}
return null;
}
So far so good but how would I implement the MenuView and the MainContentView?
I want to be able to click on menu items in the MenuView and update MainContentView and generate place tokens accordingly like:
/#MainPlace:home
/#MainPlace:storeSettings?id=<id>
/#MainPlace:userSettings
But I have no idea how to do that and how I would for example initialize my activity StoreSettingsActivity with the given id. I believe that I would need another MainActivityMapper extends ActivityMapper that now should control the place changes initiated by clicking on menu links but I just can't figure out how that could work.
I hope my question is clear, please let me know if you need some more information.
I think I once did something similar, it was not perfect because I had to deal with an existing architecture but it worked.
Here is what I did:
When a link from the menu is click execute placeController.goTo(new MainPlace(id));
In your ActivityMapper, return your MainActivity in which you set the id of the MainPlace.
In your MainActivity, in the start method call a method that will initiate your MainContentView depending on the id of MainPlace you set earlier in the MainActivity.
I am pretty sure there is a better way of doing this, but it works and it can be a start that might help you to find a better solution.
I started learning how to create an app on Android. I have a bit of knowledge on Java already, and now I'm trying some of the activity events.
I know how to use onCreate or onCreateOptionsMenu, and now I'm testing out onStop:
#Override
public void onStop(){
//a function that simply creates and return an AlertDialog.Builder object
displayPopup("Event", "Stopped", "OK").show();
}
I thought this would work since there's no error at compile time. But when I try to exit the app, I expect a popup dialog would show up but instead the app just crashed. It turns out that I need one extra line to make it work:
super.onStop();
It doesn't do anything (at least I can't see anything changed) and it's kind of useless, but without this line the app just keeps crashing.
Any help would be great, thanks.
It calls the onStop() method in the parent Activity class. When you look at the source code, you'll see that it does some internal housekeeping.
protected void onStop() {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
getApplication().dispatchActivityStopped(this);
mTranslucentCallback = null;
mCalled = true;
}
Your custom Activity extends the type Activity. The onStop() method is part of the super class activity. If you don't call super.onStop() the implementation on the Activity class is never called, and only your implementation is. This implies crashes since the onStop() method in the Activity classperforms clean ups that must be called.
The android reference on onStop() : http://developer.android.com/reference/android/app/Activity.html#onStop()
Your class is an activity subclass (extends Activity), witch mean that you must call super method of the activity mother class for more information about details of super.onstop() you can check the source code
First, sorry for my low programming skills.
I'm trying to write my first Java application for Android (actually I never studied Java but I get along with that most of all).
Anyway, I'm trying to make this app closing on Back button press. This is the code, with errors [1][2][3].
#Override
[1] public boolean onKeyDown(int keyCode, KeyEvent event)
{
[2] if ((keyCode == KeyEvent.KEYCODE_BACK))
{
[3] finish();
}
return super.onKeyDown(keyCode, event);
}
/**
* [1]KeyEvent cannot be resolved to a type
* [2]KeyEvent cannot be resolved to a variable
* [3]Cannot make a static reference to the non-static method finish() from the type
Activity
*/
Thank you all :)
You need to import KeyEvent package which is android.view.KeyEvent... import android.view.KeyEvent;
Everytime you use a class which comes from a different package of java (java.lang is the default) you should add import to say to the compiler where it should take the class. Eclipse/IntelliJ IDEA/Netbeans help you to import packages by using a simple key combination so use one of them if you can.
For error 3: Your return is out of the method body!
What is a package?
If you want to learn more about android dev, read this.
If you are using an activity, try overriding the method obBackPressed
public void onBackPressed ()
Added in API level 5 Called when the activity has detected the user's
press of the back key. The default implementation simply finishes the
current activity, but you can override this to do whatever you want.
#Override
public void onBackPressed(){
// Do some stuff
finish();
super.onBackPressed();
}
That would save you some trouble.