Android spinner.setAdapter Generates Resources$NotFoundException

Refresh

November 2018

Views

418 time

2

Greetings I am new to Android development, long time programmer (Ada, Objective-C, C++, C#) and new to Java. My code generates an exception when applying the ArrayAdapter to a spinner, namely: spinner.setAdapter(adapter); This causes my Android app to crash. Needless to say, the spinner is not displayed.

I've searched StackOverflow and have not found any really definitive answers - yet. The code (below) is practically verbatim from the Android Developers Guide.

public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

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

    // Get the spinner id.
    Spinner spinner = (Spinner)rootView.findViewById(R.id.spinner1);

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
    R.array.mission_type_array, R.id.spinner1);

    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    return rootView;

}

The array data for the spinner is located in a resource file: res\values\mission_types.xml, it is verbatim from the example.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="mission_type_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
</string-array>   
</resources>

When the code executes, spinner.setAdapter(adapter) generates an exception.

LogCat (below) indicates:

Resource ID #0x7f090006 type #0x12 is not valid
E/AndroidRuntime(6373):  at android.content.res.Resources.loadXmlResourceParser

In the Debugger, I set a breakpoint and step through the code. In the Variables window, I can click on the spinner and get info in the detail pane: android.widget.Spinner{b2dce690 VFED..C. ......I. 0,0-0,0 #7f090006 app:id/spinner1}. The Hex number #7f09 corresponds to the LogCat message above indicating "not valid".

In the Debugger Variables window, I can also drill-down into the spinner and adapter to verify the data from the resource file has been loaded.

So why, is the spinner "not valid" and what can be done to correct this?

Thank you in advance for your help. I hope to return the favor in the future. Cheers,

1 answers

2

Третий параметр createFromResoruceявляется раскладка идентификатор, используемый для создания представления, а не идентификатор блесны. Ты можешь использоватьandroid.R.layout.simple_spinner_item