Im trying to implement fragment to activity communication.
Went through android developer doc where an Activity object is passed to onAttach life cycle and set up the Fragment-Activity communication.
This documentation asks to pass Context object instead of Activity. I replaced all the Activity objects by Context objects in the life cycle method onAttach. But it is throwing a NullPointerException while calling the method of the interface from Fragment.
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
colourChangerInterface = (ColourChangerInterface) context;
}
catch (Exception exp){
System.out.println("error!");
}
}
Can anyone please give a small example of the usage in the new way ? Thanks
Edit :
Found this link where detail discussion is there on the same issue. The issue is because of the broken API 'onAttach()'; it doesn't get called at all when Context object is passed.
A simple and quick solution found from the above link is to move the code from onAttach to onCreate.
Here is a small example that will describe you the communication between
Activity
andFragment
. Suppose you have a InterfaceICommunication
. This is given below:Now you have a
Activity
nameMainActivity
that implementsICommunication
then it must have implements the methodtestMethod()
. This method will like this:Now, suppose this
MainActivity
belongs aFragment
nameTestFragment
. If you want to accesstestMethod()
of MainActivity fromTestFragment
then you can simply call using this way :Here ,
TestFragment
must be hold onMainActivity
.My related answer with source is here Thats it :)