Murat Erdogan Murat Erdogan - 1 year ago 289
Android Question

Android Snackbar NullPointerException in Fragment

I want to add a basic snackbar to my application but i have received an error that i couldn't figure out why.

I added this code in the onCreateView() method in my Fragment.

Snackbar.make(view, "Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();

And received this error:

06-01 10:26:09.955 1232-1232/? E/ActivityThread﹕ Failed to find provider info for me.muraterdogan.watchme.MetricaContentProvider
06-01 10:26:10.075 1232-1447/? E/ActivityThread﹕ Failed to find provider info for me.muraterdogan.watchme.YPLContentProvider
06-01 10:33:55.044 6646-6646/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: me.muraterdogan.watchme, PID: 6646
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.ViewGroup.getContext()' on a null object reference
at me.muraterdogan.watchme.fragments.TrendingFragment.GetData(
at me.muraterdogan.watchme.fragments.TrendingFragment.onCreateView(

Answer Source

If your Fragment is added to existing activity(Remember you can add it through xml), you should call the SnackBar's method into the onActivityCreated() method of the Fragment.

public void onActivityCreated(Bundle savedInstanceState) {
    Snackbar.make(view, "Snackbar", Snackbar.LENGTH_LONG)
        .setAction("Action", null).show();