Create a public static method in any class (but probably one that is intuitive to find*) that populates the spinner. It can take context, database, etc. as inputs, as well as the Spinner itself. Then you can call this same method from any fragment or activity and always get the same thing. Just create your layout (such as with setContentView
), get a reference to the spinner from the layout, and pass it to your populater method.
Example:
//in Activity
public void onCreate(Bundle bundle){
super.onCreate(bundle);
DatabaseHelper myDataBaseHelper = ...;//
setContentView(R.layout.my_layout);
Spinner spinner = (Spinner)findViewById(R.id.my_spinner);
Util.populateStandardSpinner(myDataBaseHelper, spinner,
getApplicationContext());
//...
}
//Another class
public class Util{
public static void populateStandardSpinner(DatabaseHelper dbHelper,
Spinner spinner, Context context) {
//Get cursor from dbHelper
//Create adapter for cursor data and apply it to spinner
}
I suppose you could also extend the Spinner class, but my preference is to avoid coding the data directly into the widget. That would break the model-view-controller design pattern.
*I sometimes just create a class called Util where I put convenient static methods like this. Or if you have a database helper class, that might be an intuitive place to put it.