I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
-
Country1 – Spot1
-
Country1 – Spot2
-
Country2 – Spot1
-
Country2 – Spot2
And so on.
This is what I thought the code should work like:
- Get selected country from spinner 1.
- Make a new ArrayList containing the spots.
- Make a second empty ArrayList.
- For each entry of the ArrayList containing the spots, check if it starts with the selected country.
- If so, add it to the second ArrayList.
- Once this is all done, make an ArrayAdapter with the second ArrayList.
- Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
- At addAll() it says: “The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)”
- At arraylist it says: “The method arraylist(int) is undefined for the type Configuration”
- At string (inside substring) it says: “string cannot be resolved”
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
arraylistuse theget(position)methodHere is your code updated, it should works or may need some tweaks