I created a Data-Base table student which contains two fields like student_id and student_name. This table contains some data for student.
My actual problem is I want to set ID and name of student in spinner like in html select tag, so when select spinner item I must get this ID to get another data from database.
You can have two arraylist for name and id;
List<String> sIds = new ArrayList<String>();//add ids in this list
List<String> names = new ArrayList<String>();//add names in this list
Then you can retrive here inside spinner select. It will work even if two names are same in the spinner which may be the case:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int id = sIds.get(position);//This will be the student id.
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
To add values into Spinner you can do it something like this Test
public class Test extends Activity
{
ArrayList<String> InfoStudent = new ArrayList<String>();
ArrayList<String> IdStudent = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//Here you'll have to make a query to get ID and Name then with
InfoStudent.add("TheID" + "InfoStudentReturnedByQuery");
//TheID should go in IdStudent ArrayAdapter and InfoStudentReturnedByQuery should go in InfoStudent ArrayAdapter
// Then you create the arrayAdapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Test.this
,android.R.layout.simple_spinner_item,difficultyLevelList);
// Set the Adapter
spinner.setAdapter(arrayAdapter);
If you want to know what spinner is selected you should do something like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"You Selected : "
+ TheMainAdapterOfStudents.get(i)+" Student ",Toast.LENGTH_SHORT).show();
}
This only it's a guide how to, hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With