Like many other programmers, I find stackoverflow an indispensable resource. To say that I’ve learned a lot over the years would be to sell it short – it’s been with me through Ruby, C#, golang, C/C++, Objective C – the list goes on. To this day, I often rely on it for quick solutions and for those, it rarely disappoints.
Every so often, however, I will come across solutions that are a little alarming. They’re not necessarily wrong in the classical sense – they likely solve the problem that the asker poses. However, the solutions are little more than attempts to plug a leaky pipe with a piece of gum. I was reminded of this again recently, when I went over a question I researched some time ago. The question is Getting the current Fragment instance in the viewpager, and while it’s not necessarily a difficult question, the highest ranking answers are little more than hacks.
The short answer to the question is that there’s no (easy) way to do what’s being asked –
FragmentPagerAdapter doesn’t currently expose a method to return the active fragment. A proper solution would involve modifying the fragments in the pager to notify the container activity when they’re displayed/hidden – and until very recently, that was a whole other can of worms. There’s also the option of rolling your own implementation of the adapter, given that Android’s support libraries are open. However, none of the top answers provide such a solution – and few mention the fact that there’s no solid way to get what’s being sought here. Instead, they provide quick and dirty hacks with a baffling number of upvotes.
This particular question isn’t necessarily anything to write home about, but it does bring up an interesting point. Given how much John/Jane Q Developer rely on SO to get random work done, how often does SO dispense flawed advice to those learning a new platform? I don’t necessarily have an answer myself – certainly this particular question is an outlier in my experience. And maybe for the vast majority of developers, a bug arising from the assumption that
"android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem() will always resolve to the correct fragment is a champagne problem – given the insane competition for market share these days. But as someone who has had to deal with quirks and idiosyncrasies of unpredictable Android configurations, these are exactly the type of bugs that are the hardest to track down – especially if the solution was used without proper understanding.
If there is a lesson to learn here, it’s that one should be careful with what he/she considers an acceptable solution. Of course, that requires a fairly solid understanding of the platform, which is probably not the case for the vast majority of folks trawling SO for answers – resulting in a sort of Catch 22.