Recyclerview adapter not working inside onResume method of fragment in Viewpager - android

I am trying to listen to a click event inside my onResume method of fragment. I have two fragments in my viewpager and if I use onResume in both the fragments only one of them is working other is not working. Below is what I am doing.
Fragment 1
public void onResume() {
super.onResume();
adapter.setOnItemClickListener(new catAdapterBlack.MyClickListener() {
#Override
public void onItemClick(String position, int pos, int posi, View v) {
... doing some stuff...
}
});
subAdapter.setOnItemClickListener(new subcatAdapter.MyClickListener() {
#Override
public void onItemClick(String position, int pos, View v) {
... doing some stuff...
});
}
Fragment 2
public void onResume() {
super.onResume();
adapter.setOnItemClickListener(new catAdapterBlack.MyClickListener() {
#Override
public void onItemClick(String position, int pos, int posi, View v) {
... doing some stuff...
}
});
subAdapter.setOnItemClickListener(new subcatAdapter.MyClickListener() {
#Override
public void onItemClick(String position, int pos, View v) {
... doing some stuff...
});
}
I am using the same adapters in both the fragments.
Now when i searched here i found this solution below but it's also not working. When i open my first fragment the app crashes with error calling MyClickListener on a null object reference.So far i have tried every method. I tried calling onresume in first Fragment and the below (setUserVisibleHint)solution in fragment two. but again its not working while the app is not crashing this way. I want to call the Myclicklistener inside both the fragments.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
init();
} else {
}
}

Move your code from onResume in onCreateView after you set the adapters.

This will work:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
// Here you need to check if your adapter is not null and initialize your adapters again
} else {
}
}
All you need is to check if your adapter is not null you may need to initialize your adapter again.

Related

How to differentiate 2 viewPager in onPageSelected

my problem is pretty simple but I don't see how to solve it... I didn't find any response to this problem.
I have 2 viewPager and when a page is selected I want to know which viewPager it comes from in onPageSelected().
There is my code :
public class MainActivity {
private ViewPager mCardsPager;
private ViewPager mIpsPager;
private MyCreditCardsPagerAdapter mCardsAdapter;
private MyInstantPaiementPagerAdapter mIpsAdapter;
private List<PayMethod> mCards;
private List<PayMethod> mIps;
//fill Pager/Adapter/List
#Override
public void onPageSelected(int position) {
if () {//If the page comes from mCardsPager
//do Something with mCards
} else { //else the page comes from mIpsPager
//do Something with mIps
}
}
}
You can set different listeners for each ViewPager rather than implement on Activity class.
Like this
mCardsPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
AND
mIpsPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
Setting same OnPageChangeListener for multiple ViewPager will not work. You need to create a class which implements OnPageChangeListener. In this class add a constructor which takes ViewPager as an input parameter and hold the value in a data member. Finally, use this class for adding OnPageChangeListener

Unable to get visible/live Fragment

I am stuck in this problem.
I want to maintain live instance of Fragment in application context. What I did is
1st Attempt
public class BaseProjectFragmentParent extends BaseProjectFragment {
#Override
public void onResume() {
super.onResume();
App.getInstance().setLiveFragment(this);
}
#Override
public void onPause() {
super.onPause();
App.getInstance().setLiveFragment(null);
}
}
and I extend all fragments by this base class. I expected live instance to be there in Application class.
Problem is in ViewPager, I have two Fragment in ViewPager where both Fragment's onResume() is called and live instance is set the second Fragment. I am working on some common code so I don't want to use getCurrentItem().
Second Attempt
Next I tried to get this Live Fragment by getSupportFragmentManager().getFragments()
isVisible() is true for both Fragments. (Not useful)
isResumed() is true for both Fragments. (Not useful)
You can use
setUserVisibleHint(boolean isVisibleToUser)
In fragments. This flag is set by the OS when a fragment becomes visible:
class MyFragment extends Fragment {
public MyFragment() {
setUserVisibleHint(false) //This is needed because by default its true
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser)
//true if fragment is visible
}
}
However this wont get called inside Viewpager. You have to add a listener to the viewpager and then set your active page manually:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});

Method call on changing tabs in viewpager

How to call a method in a fragment when the tab is changed.
I tried using onPause() in fragment, but it is not getting invoked.
I am using ViewPager.
Thanks!
You can override setUserVisibleHint(boolean isVisibleToUser) method and use it for this purpose. isVisibleToUser will be true when the tab is changed and the fragment is selected and in other fragment which was previously visible, this method will be called with false.
EDIT:
setUserVisibleHint will be called multiple times. But in that case, you can rely on getActivity() not being null. i.e. if (isVisibleToUser && getActivity() != null)
Add ViewPager.OnPageChangeListener to ViewPager by:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
<method call>
}
}
So whenever user swipes through pages of ViewPager, you will get callback in onPageSelected() method with position of that page and there you can call fragment's method
You can use interfaces here.
Define your interface in Activity that contains view pager
public interface MyInterface{
void callMethod();
}
initialize interface and call like this
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
public void onPageSelected(int position) {
myInterface.callMethod();
}
});
And implement that method in your fragment and call your method in callback.
Myfragment extends Fragment implements MyInterface{
//
#Override
void callMethod(){
//call your method here
}
}

OnClickListener called after fragment detach

I've some rare crash reports of a live app, with OnClickListener of a Gridview being called after the destruction of its parent fragment.
Here's a MCVE of the situation:
public class MyFragment extends Fragment
{
private Activity activity;
#Override
public void onAttach(Activity activity) {
super.onAttach();
this.activity = activity;
}
#Override
public void onDetach() {
super.onDetach();
this.activity = null;
}
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
activity.doSomething();
}
}
}
}
activity.doSomething() sometimes crashes with a NullPointerException. There's no other place where I write on this.activity besides onAtach() and onDetach().
I understand that a quick fix would be just checking if the Fragment isAdded() or the activity field for null, but I want to find the reason behind this crash.
Is this a bug, or expected behaviour and I should always be checking the state of the fragment?
As #M D and #shkschneider mentioned above, you should use Interface here
I have tried to provide sample here with code :
public class MyFragment extends Fragment
{
private Activity activity;
private ArrayList<DoSomethingInterface> callback = new ArrayList<DoSomethingInterface>();
private DoSomethingInterface callback1;
public MyFragment(DoSomethingInterface interface) {
this.callback1 = interface;
}
#Override
public void onAttach(Activity activity) {
super.onAttach();
this.activity = activity;
}
#Override
public void onDetach() {
super.onDetach();
this.activity = null;
}
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//activity.doSomething();
if(callback.size() > 0) {
for(int i = 0; i < callback.size(); i++) {
callback.get(i).doSomething();
}
}
if(callback1 != null) {
callback1.doSomething();
}
}
}
}
public interface DoSomethingInterface {
public void doSomething();
}
public void registerListener(DoSomethingInterface interface) {
//this.callback = interface;
callback.add(interface);
}
}
OtherActivity.java :
public OtherActivity extends Activity implements doSomethingInterface {
private MyFragment myFragmentObject;
public void onCreate() {
// pass reference to MyFragment using constructor
myFragmentObject = new MyFragment(this);
// or other way, using a method
myFragmentObject.registerListener(this);
}
#Override
public void doSomething() {
// callback will come
}
}
Basically you need to remove the listener in onDetach(). The reason is the Fragment may be amid of detaching, and a UI listener may be triggered after detached. That will confuse most apps.
Code suggestion:
#Override
public void onDetach() {
if (gridView != null) {
gridView.setOnItemClickListener( null );
}
super.onDetach();
// this.activity = null;
}
Note:
Call setOnItemClickListener() passing null as parameter. I did not find any documentation to say this but this is a known trick. Besides that, there are some listeners with custom removal methods.
I would remove code this.activity = null because this may be the code that caused the crash/exception. And conceptually it's better that the Activity class set this object instead of the Fragment class.

How to detect when a fragment appears on the screen?

How could some part of my code be aware of Fragment instance become visible on a screen?
The following snippet will explain my question.
public class MyApp extends Application {
public static final String TAG = MyApp.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
...
#Override
public void onActivityResumed(Activity activity) {
Log.d(TAG, activity.getClass().getSimpleName() + " is on screen");
}
#Override
public void onActivityStopped(Activity activity) {
Log.d(TAG, activity.getClass().getSimpleName() + " is NOT on screen");
}
...
});
}
Here i can track when any activity within my app appears on the screen. Is there any way to extend this approach on Fragments?
Something like
Activity.getFragmentManager().registerFragmentLifecycleCallbacks();
UPD. I know nothing about activities implementations, do they use fragments at all and how do they use them (injection via xml, ViewPager etc.) The only thing I have within my class is an application context. Let's assume Activity and Fragment implementations are black boxes and i am not able to make any changes.
In your fragment, override onHiddenChanged(...) method:
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
Log.d(TAG, ((Object) this).getClass().getSimpleName() + " is NOT on screen");
}
else
{
Log.d(TAG, ((Object) this).getClass().getSimpleName() + " is on screen");
}
}
Hope this work for you!
Without touching the Activity or Fragment code and assuming you don't know the tag or layout it is placed in, there is very little that you can do. The best that I can see is that you could get the FragmentManager in ActivityResumed and ActivityStopped callbacks (because here you have an Activity reference) and apply a BackstackChangedListener. This assumes that you use the backstack when changing between fragments.
The issue with what you are asking is that you want lifecycle callbacks for Fragments on the Application level when you have no control over the middle men, the Activities which are already starved for Fragment callbacks. They do most everything through their FragmentManager, and propagate their own lifecycle callbacks down to the Fragments so that the fragments will behave appropriately. The onResume and onPause callbacks in fragments only occur when they are first created or when the Activity experiences those callbacks. There is only one lifecycle callback for Fragments in Activities, onAttachFragment, which if you could override, would give you references to the Fragments that are attached to the Activity. But you said you can't change the Activity or the Fragment, and you want to know when the Fragments are shown.
So if you don't use the backstack, I don't think there's a way to do what you want.
For putting Fragments inside Activity i use SlidingTabLayout which Google uses. Inside it you have ViewPager and some Adapter to populate many Fragments. First of all you have to put this and this files in your project. Then here there is good tutorial for how you can implement SlidingTabLayout.
1) After you have implemented SlidingTabLayout in your Activity, you can detect when and which Fragment becomes visible from Activity:
mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Do nothing
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
//Whenever first fragment is visible, do something
} else if (position == 1) {
//Whenever second fragment is visible, do something
} else if (position == 2) {
//Whenever third fragment is visible, do something
} else if (position == 3) {
//Whenever fourth fragment is visible, do something
}
}
#Override
public void onPageScrollStateChanged(int state) {
//Do nothing
}
});
2) You can detect if Fragment is visible from Fragment itself as i answered here, however this may get called before onCreateView() of Fragment, so check answer in the link:
#Override
public void setUserVisibleHint(boolean visible){
super.setUserVisibleHint(visible);
if (visible){
//when this Fragment is active, do something
}
}
3) You can change also change colors of indicators of each Tab like this from Activity:
mSlidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
if (position == 0) {
return getResources().getColor(R.color.orange);
} else if (position == 1) {
return getResources().getColor(R.color.redDimmed);
} else if (position == 2) {
return getResources().getColor(R.color.yellow);
} else if (position == 3) {
return getResources().getColor(R.color.green);
} else {
return getResources().getColor(R.color.redLight);
}
}
#Override
public int getDividerColor(int position) {
return getResources().getColor(R.color.defaultActionBarBg);
}
});
Use same way as activity
set flag in application class to check visiblity of fragment, use below code in fragment
#Override
public void onStart() {
super.onStart();
Log.e( "Fragment is visible", "Fragment is visible");
Application Class.isFragmentShow = true;
}
#Override
public void onPause() {
super.onPause();
Log.e("Fragment is not visible", "Fragment is not visible");
Application Class.isFragmentShow = false;
}
to communicate with fragment you have to call that activity in which fragment added then use below code
MainFragment fragment = (MainFragment) fragmentManager.findFragmentByTag("MainFragment");
fragment.setFilter();
Don't exist a default way to do, but you can make your own Callbacks, I made this and works fine, first need have a BaseFragment class where we'll handle all fragment events.
public class BaseFragment extends Fragment {
private String fragmentName;
private FragmentLifecycleCallbacks listener;
public void registerCallBacks(String fragmentName){
// handle the listener that implement 'MyApp' class
try{
listener = (FragmentLifecycleCallbacks) getActivity().getApplication();
} catch (ClassCastException e) {
throw new ClassCastException("Application class must implement FragmentLifecycleCallbacks");
}
// set the current fragment Name for the log
this.fragmentName = fragmentName;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(listener!=null) {
listener.onAttachFragment(fragmentName);
}
}
#Override
public void onResume() {
super.onResume();
if(listener!=null) {
listener.onResumeFragment(fragmentName);
}
}
#Override
public void onStop() {
super.onStop();
if(listener!=null) {
listener.onStopFragment(fragmentName);
}
}
// 'MyApp' class needs implement this interface to handle all the fragments events
public interface FragmentLifecycleCallbacks{
void onStopFragment(String fragmentName);
void onResumeFragment(String fragmentName);
void onAttachFragment(String fragmentName);
}}
On 'MyApp' class implement the interface of BaseFragment
public class MyApp extends Application implements BaseFragment.FragmentLifecycleCallbacks{
public static final String TAG = MyApp.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStopFragment(String fragmentName) {
Log.d(TAG, fragmentName + " is NOT on screen");
}
#Override
public void onResumeFragment(String fragmentName) {
Log.d(TAG, fragmentName + " is on screen");
}
#Override
public void onAttachFragment(String fragmentName) {
Log.d(TAG, fragmentName + " is attached to screen");
}}
And now each Fragment that you have need extends 'BaseFragment' and register to the global listener
public class FragmentA extends BaseFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simple, container, false);
// here register to the global listener
registerCallBacks(FragmentA.class.getName());
return rootView;
}}
Hope this helps!
Intercept onWindowFocusChanged() in the activity and propagate that to the interested fragment.
Try this
private Boolean isFragmentVisible()
{
if(getFragmentManager().findFragmentByTag("TAG") != null && getFragmentManager().findFragmentByTag("TAG").isVisible())
{
//The fragment is visible
return true;
}
return false;
}
Alternative way
private Boolean isFragmentVisible()
{
return getFragmentManager().findFragmentByTag("TAG") != null && getFragmentManager().findFragmentByTag("TAG").isVisible();
}
You can know the following with the built in method called "onActivityCreated(Bundle)" this method tells that the fragment has been created thus you get to know that the fragment appears on the screen Click here for reference
Hope it helps
I've looked through what's available without using a base Fragment or Activity class but couldn't find any. I've made an implementation that provides basic (onAdded / onRemoved) functionality for all fragments in your application. It is certainly possible to extend it to report the current state of the fragment (onAttach, onResume, onPause, onDetach, ...).
You can find the code along with a sample here: https://github.com/Nillerr/FragmentLifecycleCallbacks
It works both for non-support library Fragments and support library Fragments through different implementations. The support library class is safer to use and should perform better, because the non-support one uses Reflection to access the fragments, while the support library FragmentManager includes a getFragments() method.
If you are setting a Fragment to your View, you probably have a container where it will be shown. Given that this container is, say, a FrameLayout with id R.id.container, you can do that:
Fragment f = fragmentManager.findFragmentById(R.id.container);
if (f instanceof YourFragment) {
// TODO something when YourFragment is ready
}
Does this interface provide anything helpful to you?
https://github.com/soarcn/AndroidLifecyle/blob/master/lifecycle/src/main/java/com/cocosw/lifecycle/FragmentLifecycleCallbacks.java
It sounds like your best bet if you can't override the Fragment's own onResume() method is to create your own interface that extends ActivityLifecycleCallbacks, then put your logging code in the onFragmentResumed(Fragment yourFragment) method.
You can get a pointer to the Fragment by doing something like this:
int yourFragmentId = 0; //assign your fragment's ID to this variable; Fragment yourFragment.getId();
FragmentManager fm = activity.getFragmentManager();
Fragment f = fm.findFragmentById(yourFragmentId);
whereever u want to check if fragment is visible or not.. just check isMenuVisible() value.
this is fragment's method which i used to check visible fragment when i have to fire some http request from viewpager selected Item.
hope this helps.
in my case i was using this method in onActivityCreated().
In you fragment override method setMenuVisibility If you are using ViewPager and are swiping from left and right, this method is called when the visivility of the fragment gets changed.
Here is a sample from my project
public abstract class DemosCommonFragment extends Fragment {
protected boolean isVisible;
public DemosCommonFragment() {
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
isVisible = menuVisible;
// !!! Do Something Here !!!
}
}
Animation listener
I have NOT checked all use cases and there is an unhandled exception. You can play around with it to fit your use case. Please feel free to comment your opinions or use cases it did not solve.
NOTE: You can add fragmentWillDisappear and fragmentDidDisappear by handling for enter in onCreateAnimation.
Parent Fragment:
public class BaseFragment extends Fragment {
private Animation.AnimationListener animationListener;
private void setAnimationListener(Animation.AnimationListener animationListener) {
this.animationListener = animationListener;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
fragmentWillAppear(animation);
}
#Override
public void onAnimationEnd(Animation animation) {
fragmentDidAppear(animation);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
#Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
AnimationSet animSet = new AnimationSet(true);
Animation anim = null;
try {
anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);
} catch (Exception error) {
}
if (anim != null) {
anim.setAnimationListener(animationListener);
animSet.addAnimation(anim);
}
return animSet;
}
public void fragmentDidAppear(Animation animation) {
}
public void fragmentWillAppear(Animation animation) {
}
}
Child Fragment:
class ChildFragment extends BaseFragment {
#Override
public void fragmentDidAppear(Animation animation) {
super.fragmentDidAppear(animation);
}
#Override
public void fragmentWillAppear(Animation animation) {
super.fragmentWillAppear(animation);
}
}

Categories

Resources