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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…