# How To Retrieve The Current `Fragment` in `ViewPager`
[SOURCE](https://stackoverflow.com/a/15261142/1602807)
The key point is to override `instantiateItem()` and `destroyItem()` of your `Fragment(State)PagerAdapter`:
```java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return ...;
}
@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(...);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
```
This seems to work for me when dealing with Fragments that are available. Fragments that have not yet been instantiated, will return null when calling `getRegisteredFragment()`. But I've been using this mostly to get the current `Fragment` out of the `ViewPager`: `adapater.getRegisteredFragment(viewPager.getCurrentItem())` and this won't return `null`.