Search code examples
androidnullpointerexceptionspinnerandroid-arrayadapterandroid-spinner

Android Spinner Array Adapter Null Pointer Exception


I am currently creating spinner with a list of fonts as shown below.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_custom_style_dialog, container, false);

    mSpinnerFont = (Spinner) getActivity().findViewById(R.id.spinnerFont);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item,
            new String[] {"System Font", "Helvetica", "Helvetica-Neue", "Impact"});
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mSpinnerFont.setAdapter(arrayAdapter);

    return view;
}

However, it is throwing a null pointer exception on the last line. I don't understand how the array has a null value. Thanks for your responses.

Spinner XML Below

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.richluick.blocnotes.CustomStyleDialogFragment">


    <Spinner
        android:id="@+id/spinnerFont"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</FrameLayout>

Solution

  • This line:

    getActivity().findViewById(R.id.spinnerFont);
    

    looks for a view from root view associated with the activity (set by Activity.setCurrentView()), while your spinner is inside the view you have just inflated from file (it is not placed to Activity's view hierarchy yet). Fix your code to:

    view.findViewById(R.id.spinnerFont);