Prasham Trivedi

Adventures after Google I/O-1(Snackbar).

June 04, 2015

1 minute to read.

Google I/O-2015 has full of excited news for developers. Mainly being Android Developers, there are too many new announcements like M developer preview, design support library, Databinding plugin, GCM etc. Except M preview I have decided to try other android related new things. Normally Google has some nice documentation and support and their code mostly works seamlessly without any problems. However that’s not always the case, I have discovered (and currently discovering) how these changes are affecting our daily codes and can lead into some problems. There are some problems with some codes and I am documenting as much of information as I can with the help of this series called Adventures after Google I/O. However those problems are reason of bad coding practice or some other things, all things are not necessarily Google’s problem. In this series I will post what is (or can go) wrong, and will tell you the workaround if exists.

In the inaugural part, I will tell you some crucial things about snackbar.Google Released Design Support Library to backport Material Design Stuffs (Like FAB, Snackbars, Animations etc..) in Google I/O. Many developers including me were using third party solutions for many of this components. And many are changing their codebase to adopt to Design Support Library.

There are many trivial things written about FAB and Co-Ordinator layout with Toolbar in various blogposts and Medium.com, I have discovered a thing to take care about Snackbar. Here is what I have discovered.

Before moving to design support library, I have been using Snackbar Library to show Snackbar.Previously, it wasn’t required to pass any view to Snackbars. But with design support libraries it is required to pass the view.

What is problematic:

In current project of mine, all the views are inflated in a fragment, which itself inflated in activity Via XML. Like me,i f you are using your fragments such a way, showing Snackbar will throw exception all the time.

As you have seen in Snackbar section, Snackbar.make() method requires a View. So that it can find its parent where it can inflate Snackbar there. And if you are inflating a fragment from XML, it will not have any parent view, thus throwing NullPointerException when you show Snackbar.

Workaround:

Work around is simple and exists from day one, don’t directly inflate your fragments from XML. Instead add/replace them using fragment manager.

You can easily face this situation if you are using Android Studio’s new activity with fragment template. IMO inflating fragments in XML is bad for debugging and if any of the library requires a parent view, you will face NPEs all the time.

Next In the series: Google Cloud Console and iOS.

comments powered by Disqus