I want to create an application with two Spinners. When you select one of the items inside the first spinner, the second spinner will get only a few items (depends on which item selected).
For example: in the first spinner I select "Mazda", and then on the second I will be able to see only Mazda's models, not BMW, Ford etc. Can I do something like this?
I tried to create a spinner without items, and set the entries of the spinner on the XML when item selected, but there is no method to do this.
I don't create Lists. I want to create string-array resources in my strings.xml, and give that array to the second spinner.
Of course it is doable and pretty straightforward. Spinners works with the model provider, which in Android it is called Adapter pattern. So what you can do is put in your first spinner an adapter that holds all the brands of your cars, and listen on the first spinner for changes using setOnItemSelectedListener.
When the item changes, you can create a new adapter instance for the second spinner with the only values that are valid in this case.
Try following code. I've organized the sample data in a HashMap but you can do it in your own way.
// hashmap object containing data of spinner1 as 'keys' with relevant
// data of spinner2 in List<String> object as 'values'
final Map<String, List<String>> data = new HashMap<>();
data.put("A", Arrays.asList("1","2","3","4"));
data.put("B", Arrays.asList("4", "5"));
data.put("C", Arrays.asList("6", "7", "8", "9"));
data.put("D", Arrays.asList("10", "11", "12"));
data.put("E", Arrays.asList("13", "14"));
// obtaining a string array containing keys(data of spinner1) of above hashmap
final String[] dataSpinner1 = new String[data.keySet().size()];
data.keySet().toArray(dataSpinner1);
// initializing an string type, ArrayAdapter for spinner1
// you will need to pass activity context, layout for the spinner item and
// spinner content(as string array) as arguments to create an array adapter
final ArrayAdapter<String> spinner1Adapter = new ArrayAdapter<String>(context, R.layout.spinner_layout, dataSpinner1);
spinner1.setAdapter(spinner1Adapter);
// setting listner for spinner1 to trigger when an spinner item is being
// clicked by the user
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// obtaining relevant data for spinner2
List<String> dataSpinner2 = data.get(dataSpinner1[position]);
// crating an setting array adapter for spinner2
ArrayAdapter<String> spinner2Adapter = new ArrayAdapter<String>(context, R.layout.spinner_layout, dataSpinner2);
spinner2.setAdapter(spinner2Adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Related
I have a spinner whose elements set by an arrayList.this arraylist gets data by calling an api. I have set title at 0th position of arrayList .the problem is i want to show this title as activity is created. but this will set only when api calling is successful .it takes some time to load data. can anyone give me better idea to set title to spinner.
If data comes from api then you can add dialog on screen and hide title until api call success.. when you get response true then show titleview and add title from api. and api response is false then show error.. so user will get better view..
Thanks
Do like this
ArrayAdapter stringArrayAdapter = new ArrayAdapter(this,
R.layout.spinner_item, CatagoryName);
// create a spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// add adapter to spinner
spinner.setAdapter(stringArrayAdapter);
// create listener and add to spinner
spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
// put code which recognize a selected element
}
Try this way
ArrayList<String> list = new ArrayList<>();
list.add(0,"Please Select");
ArrayAdapter stringArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, CatagoryName);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(stringArrayAdapter);
// now call the API for data
//After data received, you have to make temp list to store response
ArrayList<String> Templist = new ArrayList<>();
//Templist = Server response
//now add templist in main List
list.addAll(Templist);
// and call this
stringArrayAdapter.notifyDataSetChanged();
I have a spinner:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int childposition, long id) {
textView.setText(spinner.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText("");
}
});
Above you'll see that textView - is my text object. I'm displaying a text item spinner in the textView when I click it. If I dont click the spinner then my textView must be textView.setText("");
But the spinner is always set text in my textView, even if I do not choose spinner.
Question
How can I accomplish this?:
If I dont choose item spinner, textView is empty: textView.setText("");
If I do choose the item spinner, textView gets: textView.setText(spinner.getSelectedItem().toString());
String item = parent.getItemAtPosition(childposition).toString(); //Get selected item
if(item.equals("spinner")){ // Check if it equals spinner
textView.setText(item); // Set text to item
}else{
textView.setText(""); // If it doesn't equal spinner set text to ""
}
If I understood the question right, putting this instead of textView.setText(spinner.getSelectedItem().toString()); and deleting content of onNothingSelected should do the trick.
UPDATE
I finally understood what you mean. To do this create your spinner like this and add "" as first choice in your string-array resource :
String[] newArray = getResources().getStringArray(R.array.yourArray);
List<String> myResArrayList = Arrays.asList(newArray);
ArrayList<String> spinnerItems = new ArrayList<String>(myResArrayList);
//Making adapter with ArrayList instead of String[] allows us to add/remove items later in the code
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerItems);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinnerItems.remove(0);
adapter.notifyDataSetChanged(); // Here we remove the first choice which is "" so the user won't be able to select empty.
if i have 2 spinner the second depend in the first
i will retriever the info of the second spinner from MySQL database depend in the choose of first spinner i succuflly get the id of the first spinner but i do not
how to send it to the other cause it not work with me
i have class MainActivity that have:
new LoadAllCourses().execute(); //first spinner generation
new LoadAllSection().execute(); //second spinner
in class LoadAllCourses extends AsyncTask<String, String, String>
adapter1 = new MyCustomAdapter(MainActivity.this,
android.R.layout.simple_spinner_item,
coursesList);
spinner1.setAdapter(adapter1); // Set the custom adapter to the spinner
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
HashMap<String, String> map12 = coursesList.get(position);
String id3 = map12.get("CourseID");
// Do something
Log.d("All coursesdddddddddddddddddddddddddddddddddddd: ", id3);
// Do something
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
});
now i want to get the id3 and send it to
class LoadAllSection extends AsyncTask<String, String, String>
but it is not work
how can i solve it if i have as i said
If I have understood your question, you require the selection on the first spinner to for the basis of a search from a database to populate the second spinner.
If in adapter 1 (adapter1 = new MyCustomAdapter(MainActivity.this,
android.R.layout.simple_spinner_item,
coursesList);) courseList is an array, one can get the selected item from the spinner in the setOnItemSelectedListeneras follows courseList [position].
Having obtained the selected item, you then require a function to perform the query in the database, say load_all_selection(courseList [position]) which should return an array of results from your database.
Since it returns an array you can define adapter 2 as follows
adapter2 = new MyCustomAdapter(MainActivity.this,
android.R.layout.simple_spinner_item,
load_all_selection(courseList [position]));
and assign it to the second spinner spinner2.setAdapter(adapter2);
All this can be done from within the setOnItemSelectedListener part, except maybe for the definition of the load_all_selection(...) function.
I hope I understood you question and this helps. If it doesn't you can still look around for a different solution.
I have one ListView and one Spinner. The Spinner is situated at the right top of the layout. My ListView contains some names (eg. country names) and the spinner has some alphabets (a-z). Suppose if I choose the letter "f" from the Spinner, my ListView must show the country names that starts only with the letter "f" . I want to sort my ListView by values from the Spinner?
You need to implement a Filter for your ListView. Everytime the OnItemSelectedListener of your Spinner gets called you need to filter the items. If you're not sure how to implement a filter in your ListView's adapter have a look at this: Filtering ListView with custom (object) adapter
I guess there won't be any way around implementing an own ListAdapter (it's easy).
Try to use the getFilter() method of the ListView adapter:
String[] filterL = { "a", "b", "c" }; //etc
//...
Spinner spin = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<String> aspin = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filterL); //the adapter for the Spinner
aspin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aspin);
final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, countries); //the adapter for the list
setListAdapter(aa); //set the adapter for the list(if you extend LisActivity) or call setAdapter on the ListView element
//add the listener:
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
boolean status = false;
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3) {
if (!status) {
status = true;
return;
}
aa.getFilter().filter(filterL[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I have a question that, I want to load items in a spinner on ItemClick of another Spinner. Actually I two spinners, data is loaded into first spinner from json_parsing and I have to load data in second Spinner after selecting an item from first spinner, So, I don't know how it will implemented? Please suggest me the right solution.
Thanks in advance.
You can do it like this,
First time you data will be loaded in First and Second Spinner.
On Selection of item from First Spinner do this.
1.) Clear the previous ArrayList or Array whateven you have passed the
Second Spinner.
2.) Fill the ArrayList or Array of new data & Update the Second Spinnner using
adapter.notifyDataSetChanged();
second_spinner.setSelection(0);
First Set an OnItemClickListner for your First Spinner. In the OnItemClickListner Method first parse your XML. After completing XML parsing, set parsed data to the adapter and set that adapter with your second spinner
Set an OnItemClickListener on your first spinner that would prepare and set the adapter to the second spinner.
Here is a more complete code example:
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Cursor c1 = (some code for getting a cursor from an data source, for example, a sqlite database)
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c1, new String[]{"column_name"}, new int[]{android.R.id.text1});
spinner1.setAdapter(adapter1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
Cursor c2 = (some code for getting a cursor from an data source, for example, a sqlite database)
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c2, new String[]{"column_name"}, new int[]{android.R.id.text1});
spinner2.setAdapter(adapter2);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Cursor c_new = (create a new cursor);
adapter2.changeCursor(c_new);
adapter2.notifyDataSetChanged(); // this is important for notifying the UI
spinner2.setAdapter(adapter2);
}
});
What you do is set a listener to the first Spinner, there change the Cursor of the second Adapter to a new one, notify the UI and reset the Adapter of the second Spinner.