yudi yudi - 1 month ago 9
Android Question

Android - control list of 2nd Spinner item select based on 1st spinner selection

I am using 2 spinners in my app, 1st spinner is an array of

lecturer
, and 2nd spinner is an array of
courses
,

and this is an output of json in 1st spiner:
ardi halim, fanny, indah, [...]

and for 2nd spinner output look like:
mobile development, object-oriented programming, [...]

my question is how to control the 2nd spinner list when 1st spinner already select the `lecturer?

for the example :


  1. when 1st spinner choose ardi halim, the 2nd spinner giving a list
    of mobile development and OOP

  2. when 1st spinner choose fanny, the 2nd spinner giving a list of mobile development only



i just can control the 2nd spinner using
setSelected
with this code :

if(text.equals("Fanny")){
Toast.makeText(MainActivity.this,"Anda Memilih Dosen Fanny", Toast.LENGTH_SHORT).show();
sp2.setAdapter(adapter2);
sp2.setSelection(1);
sp2.setEnabled(false);
}


but how to add more than 1 list in 2nd spinner when someone choose
ardi halim
?

I've tried searching for a posting someone who has the same problem but I have not found the answer

Answer

You have to make class like this for handling 2nd spinner according to your 1st spinner result

public class Lecturer{
String name;
ArrayList course;
Lecturer(String name,Arraylist course){
this.name= name;
this.course = course;
    }

public String toString(){
return name;
}
}

In Activity

ArrayList<Lecturer> lecturerList = new ArrayList<>();
list.add(new Lecturer("ardi halim",<courses list for ardi halim>));
list.add(new Lecturer("fanny",<courses list for fanny>));

set lecturerList for 1st spinner
then
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        ArrayList courselist = ((Lecturer)spinner1.getSelectedItem()).course;
                set courselist for spinner2 adapter
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });