LinearLayout bottomSheetViewgroup = (LinearLayout) findViewById(R.id.bottomSheet);
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetViewgroup);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); //this line
I have this code within my activity's onCreate() method and I'm getting the below NPE exception when the last line is executed:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference at android.support.design.widget.BottomSheetBehavior.setState(BottomSheetBehavior.java:440)
The issue with your code is you are trying to call the setState method directly inside onCreate. This is will throw a nullPointer because the WeakReference is not initialized yet. It will get initialized when the Coordinator layout is about to lay its child view.
So the best approach is set the peek height to 0 and show/hide inside the onItemClick listener.
I have answered this question here: https://stackoverflow.com/a/36236743/1314796
You can also consider listening to the global layout event, this way you'll be sure that the bottomsheet has been laid out when setting the collapsed state.
I've found a solution but I still don't known why this happen. The solution is put this last line to user call directly after the activity is running. Ex: in a contextMenu callback or in any OnClickListener.
While Sanf0rds answer is correct, it doesn't allow the ability to define the BottomSheet as expanded by default. The issue is caused by the WeakReference not being set until the last line of onLayoutChild.
The solution is to provide our own class which extends BottomSheetBehavior, but setting the state inside an overridden onLayoutChild. The code is provided below.
uk/ac/qub/quibe/misc/ExpandedBottomSheetBehavior.java
In the layout file reference reference your new custom behavior.
Change
To