HesZrave HesZrave - 3 months ago 21
Android Question

createFromResources() in ArrayAdapter cannot be applied to spinner

Im having trouble when creating an ArrayAdapter on my spinner. i don't know how to explain to you guys but people say a picture speaks 1000 words. so i provide a picture of my problem. please help me i really dont know what to do know.

this is my error

this is my class

public class SettingFragment extends Fragment{

private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

public SettingFragment(){
//required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);

spinner = (Spinner)rootView.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

return rootView;
}


}

this is my string.xml

<string-array name="select_font_size">
<item>Small</item>
<item>Default</item>
<item>Large</item>
<item>Larger</item>
</string-array>


and this is my xml code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">


<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:layout_gravity="center_horizontal" />



Answer

I'd suggest to move the creation of the adapter inside the onActivityCreated callback when you know for sure that by calling getActivity() you will get a not null instance of the activity:

public class SettingFragment extends Fragment{

private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

public SettingFragment(){
    //required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_setting, container, false);
    spinner = (Spinner)rootView.findViewById(R.id.spinner);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    adapter = ArrayAdapter.createFromResource(getActivity(), R.array.select_font_size, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
    }
}
Comments