Reputation: 51
I have a Activity with two fragments. One of them hava a spinner. When I populate it the app crashes. I don't know why. In android developers it's confused how do it in fragments, it seems is diferent like normal activity.
Thanks!
public class InstrumentsFrag extends Fragment {
TextView tv1;
Spinner sp;
String[] os = {"Cupcake v1.5", "Donut v1.6", "Éclair v2.0/2.1", "Froyo v2.2",
"Gingerbread v2.2", "Honeycomb v3.0/3.1"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.instruments, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = (Spinner) getActivity().findViewById(
R.id.spinner1);
ArrayAdapter <CharSequence>adapter = ArrayAdapter.createFromResource( getActivity(), R.array.sections , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
Upvotes: 3
Views: 9781
Reputation: 111
I had the same problem where my app crashed when populating a spinner. In my case, the spinner I was populating was defined in the fragment's XML file, so the trick was getting findViewById() to find it. I see in your case you tried to use getActivity():
sp = (Spinner) getActivity().findViewById(R.id.spinner1);
I also tried using both getActivity() and getView(), and both caused crashes (null spinner, and NULL Pointer exception respectively).
I finally got this to work by replacing getActivity() with the fragment's view. I did this by populating the spinner when onCreateView() is called. Here are some snippets from my final code:
private Spinner spinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.myFragmentXmlFile, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
...
}
private void setSpinnerContent( View view )
{
spinner = (Spinner) view.findViewById( R.id.mySpinner );
...
spinner.setAdapter( adapter );
...
}
So I passed the fragment view into my function and referenced that view to configure the spinner. That worked perfectly. (And quick disclaimer - I'm new to Android myself, so perhaps some of the above terminology can be corrected or clarified if needed by more experienced people.)
Hope it helps!
Upvotes: 11