MrEngineer13 / SnackBar

toast-like alert pattern for Android inspired by the Google Material Design Spec

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

NullPointerException when instantiated using `SnackBar(Context, View)`

carltonwhitehead opened this issue · comments

Example code:

SnackBar snackBar = new SnackBar(getContext(), SomeCustomCompoundView.this);

Stack trace:

   Process: com.example.app, PID: 12578
    java.lang.NullPointerException
            at com.github.mrengineer13.snackbar.SnackBar.init(SnackBar.java:108)
            at com.github.mrengineer13.snackbar.SnackBar.<init>(SnackBar.java:102)
            at ...

I suspect this might be due to an invalid usage of SnackBar, but I wanted to get some input since it's not clear. I'm calling this within a compound view which is part of a ListView. With the given method signature, I would expect SnackBar to be able to find the appropriate "snack container" in the view hierarchy. From looking at the constructors in SnackBar at

it seems SnackBar only inflates its layout container into the Activity's layout when the SnackBar(Activity) constructor is called, and not when the SnackBar(Context, View) constructor is called.

I was able to work around this error by inserting the following include tag into my layout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@id/snackContainer"
        layout="@layout/sb__snack"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

    <FrameLayout
        android:id="@+id/root_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/snackContainer"
        android:layout_alignParentTop="true" />

</RelativeLayout>

I'm using the include in a RelativeLayout, but it would probably work inside a LinearLayout as well. This also has the added benefit of pushing the main content up so that the SnackBar doesn't block any views that are at the bottom of the content view.
Then I created a SnackBar by getting the snackContainer view:

//Being used inside a fragment
SnackBar snackBar = new SnackBar(getActivity(), getActivity().findViewById(R.id.snackContainer));

I have not tested it extensively, but it appears to work well for my purposes and since I essentially recreated what the SnackBar(Activity) constructor does, with a little extra layout control, I don't see why it shouldn't work anywhere the Activity constructor does. It would be much easier to be able to add a ViewGroup subclass into the layout and have the SnackBar automatically inflate into it like it does with android.R.id.content though.

Are you still getting this with the latest version of SnackBar?